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

try {
      ConnectionManager::getDataSource('default')->disconnect();
      ConnectionManager::drop('default');
      ConnectionManager::create('default', $this->config);
      ConnectionManager::getDataSource('default')->connect();
      $db = ConnectionManager::getDataSource('default');
    } catch (MissingDatabaseException $e) {
      $this->Session->setFlash($e->getMessage()); 
    }

where $this->config is user based connection.

To switch back to default file based connection I do:

try {
      ConnectionManager::getDataSource('default')->disconnect();
      ConnectionManager::drop('default');
      $dbconfig = new DATABASE_CONFIG();
      ConnectionManager::create('default', $dbconfig->default);
      ConnectionManager::getDataSource('default')->connect();
      $db = ConnectionManager::getDataSource('default');
    }

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

Leave a Reply