CakePHP: switching between multiple databases

Relating to a post I submitted a while back, along with creating a data connection on the fly I had to switch between two connections. That is, file based default connection and a dynamic connection based on user. Here is the scenario.

I have two types of connections. One is the default core connection which uses the Config/database.php file for connection configurations. Second one is a dynamic configuration which uses db details saved for logged in user. So, for a few specific actions I have to switch between the default db connection and user based db connection. Here’s how it came up.

To switch to user based db connection from default file

where $this->config is user based connection.

To switch back to default file based connection I do:

where $dbconfig->default i.e. $default contains my default connection configuration in Config/database.php

Leave a Reply