Skip to content

Instantly share code, notes, and snippets.

@bmack
Last active October 14, 2021 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmack/55a167e173313aa5aff2c59fead83082 to your computer and use it in GitHub Desktop.
Save bmack/55a167e173313aa5aff2c59fead83082 to your computer and use it in GitHub Desktop.
PrimaryReplicaConnection for TYPO3 Doctrine DBAL
<?php
// Runs through a pool of connections and see which one can connect to
$GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['wrapperClass'] = \PrimaryReplicaConnection::class;
class PrimaryReplicaConnection extends \TYPO3\CMS\Core\Database\Connection
{
public function connect(): bool
{
$allParams = $this->getParams();
try {
return parent::connect();
} catch(\Doctrine\DBAL\Exception\ConnectionException $e) {
if (!isset($allParams['replica'])) {
throw $e;
}
}
while ($nextReplica = array_shift($allParams['replica'])) {
$allParams = array_replace_recursive($allParams, $nextReplica);
$driverOptions = $allParams['driverOptions'] ?? [];
$user = $allParams['user'] ?? null;
$password = $allParams['password'] ?? null;
try {
$this->_conn = $this->_driver->connect($allParams, $user, $password, $driverOptions);
if ($this->_eventManager->hasListeners(\Doctrine\DBAL\Events::postConnect)) {
$eventArgs = new \Doctrine\DBAL\Event\ConnectionEventArgs($this);
$this->_eventManager->dispatchEvent(\Doctrine\DBAL\Events::postConnect, $eventArgs);
}
return true;
} catch(\Doctrine\DBAL\Exception\ConnectionException $e) {
continue;
}
}
// No connection available
if ($e) {
throw $e;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment