We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Dynamic database connections

Is it possible with Phalcon to register a database connection based on the logged in user.

E.g. System will host multiple accounts, each account will have its own database.

All users credentials are saved in the main database, user logs in via main database, once logged in, their account specific database credentials should be loaded for the secondary connection.

So in essence, I guess I am looking for a way to register the database service from a controller?

I hope this is clear. Any help would be appreciated, thanks.

You could use multiple db functionality. One db as your main db and the second one based on logged user. the only thing that you should handle is initializing the second DB connection after user successful login and assigne it to your app DI. I thinks it's the best solution for your case

for more information see official documentation



4.6k

You could use multiple db functionality. One db as your main db and the second one based on logged user. the only thing that you should handle is initializing the second DB connection after user successful login and assigne it to your app DI. I thinks it's the best solution for your case

for more information see official documentation

Hi Aboozar, Thanks for your comment, I have previously read that documentation but cannot work out how to implement it in my scenario. Once the user has logged in, their account id is saved to the session, how can I add a new connection to the di after the services have already been registered in the module? As the module cannot read the session until it has fully loaded?

You can access the DI using:

Phalcon\DI::getDefault();

So once the user has logged in, you might be able to do:

// assuming $db_username, $db_password, $db_db are all set:
Phalcon\DI::getDefault->setShared('user_db',function() use($db_username,$db_password,$db_db){
    // run whatever code you need to create the connection

    return $DatabaseConnection;
}

i would like to know the same thing... I have the same problem When i set the connection into DI, not applied in global context