I have a Core config Database, each row is an \'App\' with some basic config etc.
Once you have chosen your app, I want to connect to a database using a property of that
In symfony 4, you can pull it off with a wrapper class:
# doctrine.yaml
doctrine:
dbal:
connections:
default:
wrapper_class: App\Service\Database\DynamicConnection
The class simply extends the original Connection:
class DynamicConnection extends \Doctrine\DBAL\Connection
{
public function changeDatabase(string $dbName)
{
$params = $this->getParams();
if ($this->isConnected())
$this->close();
if (isset($params['url'])) {
$params['url'] = preg_replace(
sprintf("/(?<=\/)%s/", preg_quote($this->getDatabase())),
$dbName,
$params['url']
);
}
if (isset($params['dbname']))
$params['dbname'] = $dbName;
parent::__construct(
$params,
$this->_driver,
$this->_config,
$this->_eventManager
);
}
}