Using more than one database connection in CakePHP
CakePHP, Development, Frameworks, Labs, PHP April 10th, 2008
Probably is pretty obvious for most of the advanced users, but when I started my experience with CakePHP I read a lot of configuring a database, but not multiple ones. There are articles how to use database for development and for production without changing anything but rewriting a function in DATABASE_CONFIG class.
These days we need to choose way of splitting the functionality and we have to decide: Shall we use different databases or shall we put a prefix for every table. So far we choose to use prefix, but I dig into this and I realized that every model could be attached to different database.
Here is the example how to do this:
...
var $useDbConfig = 'other';
...
}
so this variable $useDbConfig is the trigger which linking the model to different databases defined in the DATABASE_CONFIG class.
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user1',
'password' => 'pass1',
'database' => 'db1',
'prefix' => ''
);
var $oher = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user2',
'password' => 'pass2',
'database' => 'db2',
'prefix' => ''
);
}
When I am thinking more and more it’s quite handy, especially if you want to connect different databases like Oracle, MySQL or Postgresql together.
Of course this could be created automatically with Bake script, because before start baking Model(s) it ask which connection do you want to use. So it’s pretty easy.
Hope this help somebody.
Add to:


[...] I read a lot of configuring a database, but not multiple ones. This article show you how to do it.read more | digg story Share and Enjoy: These icons link to social bookmarking sites where readers can [...]