I've done something similar in a project of mine, here's my working solution:
First, define a empty connection into your config.yml
dynamic_con:
dbname: ~
user: ~
password: ~
host: ~
charset: UTF8
Now, I've written an PostLoginController
, which will always be called after an successful login.
There, I get my connection data and call my DynamicDatabaseService
with it.
My DynamicDatabaseService
has the following function, that will construct my connection with the data provided.
public function getDynamicDatabase()
{
// $this->doctrine was given to the service in the constructor beforehand
$dynamicCon = $this->doctrine->getConnection('dynamic_con');
$refCon = new \ReflectionObject($dynamicCon);
$refParams = $refCon->getProperty('_params');
$refParams->setAccessible('public');
if($params == false){
$defaultCon = $this->doctrine->getConnection('default');
$params = $refParams->getValue($dynamicCon);
// You need to inject your Params to the function or implement some further logic to receive your connection parameters to use them here.
$params['dbname'] = $dbName;
$params['user'] = $dbUser;
$params['password'] = $dbPass;
$params['host'] = $dbHost;
}
$refParams->setValue($dynamicCon,$params);
$refParams->setAccessible('private');
return $dynamicCon;
}
Now, you can work with the $dynamicCon
as a normal PDO Connection, so
$dynamicCon->prepare("SELECT * FROM USERS WHERE id = :id");
$dynamicCon->bindValue(":id", $id);
$dynmicCon->execute();
And so on