CakePHP Create Datasource on the fly

Want to switch between different databases in a CakePHP action? Do you want to use different database for different clients or sites? Don’t worry the solution more simpler than you thought it to be.

Following this linkĀ and few other similar links this is how I connected to different datasource in CakePHP.

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 contains the following set of data:

array(
	'password' => '*****',
	'login' => 'dbusername',
	'host' => 'dbhostname',
	'database' => 'dbname',
	'datasource' => 'Database/Mysql'
)

One thought on “CakePHP Create Datasource on the fly

Leave a Reply

Your email address will not be published. Required fields are marked *