Friday, December 16, 2011

Dynamic database connection in CakePhp

I encountered this scenario at work wherein I have the same logic, same structure but using different brands. The problem is their database name and connection is different. Below is the solution I found:

Step 1: Create your database connection in database.php
var $brandXConfig = array(
 'driver' => 'postgres',
 'persistent' => false,
 'host' => 'localhost',
 'login' => 'root',
 'password' => '',
 'database' => 'brand_x',
 'prefix' => '',
 //'encoding' => 'utf8',
);


var $brandYConfig = array(
 'driver' => 'postgres',
 'persistent' => false,
 'host' => 'localhost',
 'login' => 'root',
 'password' => '',
 'database' => 'brand_y',
 'prefix' => '',
 //'encoding' => 'utf8',
);

Step 2: Add this function to app_model.php
Class AppModel extends Model
{
     function changeDataSource($newSource)  {
          parent::setDataSource($newSource);
          parent::__construct();
     }
}

Step 3: Add this function to app_controller.php
Class AppController extends Controller
{
     function changeDbSource($database = 'default') {
          $db = ConnectionManager::getInstance();
          $connected = $db->getDataSource($database);
          if($connected->isConnected()) 
                return true;
          return false;
     }
}

Step 4: Add this to your model
function changeMyDb($brand)
{
     if($brand == 'brandX') {
          $this->changeDataSource('brandXConfig');
     }
     else if($brand == 'brandY') {
          $this->changeDataSource('brandYConfig');
     }
}

After doing this, you'd be able to change your database connection as needed.

No comments:

Post a Comment