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;


  1. Ricardo Stuven
    Posted February 26, 2006 at 1:08 am | Permalink

    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);

  2. Posted May 6, 2006 at 7:21 am | Permalink

    Very, very nice, i have 2 databases, one for users and other for content. :-) But, how can i change “on the fly”?

  3. Posted May 6, 2006 at 8:51 am | Permalink

    @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’;

%d bloggers like this: