Switch your database configuration based on some criteria
Currently, I am experimenting with unit tests. These tests should use an own database. And so I defined a “test” configuration in app/config/database.php:
var $test = array('driver' => 'mysql',
'connect' => 'mysql_pconnect',
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'project_name-test',
'prefix' => '');
But it does not automatically use the “test” configuration when I run a test. So I wrote a constructor for app/config/database.php based on the idea from http://wiki.cakephp.org/tutorials:change_database_config, which switches the database configuration based on the request url (thanks to gwoo for the hint):
function __construct ()
{
if (strstr($_SERVER['REQUEST_URI'], ‘/tests’))
{
$this->default = $this->test;
}
}




I use a similar approach, but in AppModel. Using your condition, it would look like this:
function __construct($id=false, $table=null, $ds=null)
{
if (strstr($_SERVER['REQUEST_URI'], ‘/tests’))
{
$this->useDbConfig = ‘test’;
}
parent::__construct($id, $table, $ds);
}
Very, very nice, i have 2 databases, one for users and other for content. :-) But, how can i change “on the fly”?
@tiago: I am not quite sure what you try to accomplish. If model A should be stored in database 1 and model B should be stored in database 2, then you can set the variable $useDbConfig in your models:
var $useDbConfig = ‘yourDBConfiguration’;
I’ve got a little something here:
http://walkerhamilton.com/453/advanced-database-switching-in-cakephp
Advanced DB switching on my app.
@Walker: Thanks for the link.