Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
$conn = \Doctrine\DBAL\DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Connections\MasterSlaveConnection',
'driver' => 'pdo_mysql',
'keepSlave' => true,
'master' => array(
'user' => 'ideato',
'password' => 'ideato',
'dbname' => 'db_ideato'
),
'slaves' => array(
array(
'user' => 'ideato',
'password' => 'ideato',
'dbname' => 'db_ideato_slave'
)
)
)
);
$entityManager = EntityManager::create($conn, $config);
//read on slave
$productRepository = $entityManager->getRepository('Product');
$products = $productRepository->findAll();
//write on master
$product = new Product();
$product->setName("nuovo_prod1");
$product->setCategory("oeeooeoe");
$entityManager->persist($product);
$entityManager->flush();
echo "Created Product with ID " . $product->getId() . "\n";
//now connection remains on master
//get masterslave connection
$masterSlaveConn = $entityManager->getConnection();
$masterSlaveConn->getWrappedConnection();
//switch connection on slave
$masterSlaveConn->connect('slave');
var_dump($masterSlaveConn->isConnectedToMaster()); //false
//read on slave
$productRepository = $entityManager->getRepository('Product');
$products = $productRepository->findAll();
foreach ($products as $product) {
echo sprintf("-%s\n", $product->getName());
}
//switch connection on master
$masterSlaveConn->connect('master');
//read on master
$productRepository = $entityManager->getRepository('Product');
$products = $productRepository->findAll();
foreach ($products as $product) {
echo sprintf("-%s\n", $product->getName());
}
var_dump($masterSlaveConn->isConnectedToMaster()) ;//true
//switch connection on slave
$masterSlaveConn->connect('slave');
//read on slave
$productRepository = $entityManager->getRepository('Product');
$products = $productRepository->findAll();
foreach ($products as $product) {
// echo sprintf("-%s\n", $product->getName());
}
var_dump($masterSlaveConn->isConnectedToMaster()); //false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.