Geo Geo - 5 months ago 33
PHP Question

Symfony Doctrine Dynamic Configuration

I currently have a problem with doctrine connexion on my Symfony 3 project.

here is the connection diagram to the database that I should implement:

1 - request on a external database containing the server, login and application database password

2 - decrypt password

3 - configuration / doctrine connection

I don't know if I should rather work on

or with another method?

What is the recommended method in this case ?


I've done something similar in a project of mine, here's my working solution:

First, define a empty connection into your config.yml

    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');
    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;


    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);

And so on