Master/Slave DBAL connections with Symfony 4

If using DBAL without the Doctrine bundle you may want to set up a master/slave connection. There are a couple of gotchas if trying to discern the correct format from the bundle configuration.

  • connection params don’t work with the url connection format
  • wrapperClass not wrapper_class
  • specify the MasterSlaveConnection as the class type
  • use the factory method getConnection
  • the slaves are defined as a separate param to master rather than under it
#services.yml
# ...
db.default:
class:
Doctrine\DBAL\Connections\MasterSlaveConnection
factory: Doctrine\DBAL\DriverManager::getConnection
arguments:
$params:
wrapperClass:
Doctrine\DBAL\Connections\MasterSlaveConnection
driver: pdo_mysql
master:
host: '%env(DATABASE_MASTER_HOST)%'
port:
~
user: '%env(DATABASE_MASTER_USER)%'
password: '%env(DATABASE_MASTER_PASSWORD)%'
dbname: '%env(DATABASE_MASTER_DBNAME)%'
charset:
UTF8
slaves:
-
host: '%env(DATABASE_SLAVE_HOST)%'
port:
~
user: '%env(DATABASE_SLAVE_USER)%'
password: '%env(DATABASE_SLAVE_PASSWORD)%'
dbname: '%env(DATABASE_SLAVE_DBNAME)%'
charset:
UTF8

Doctrine\DBAL\Connection: '@db.default'

Like what you read? Give Peter Lafferty a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.