Database switching in CakePHP

Published: on 9/9/08 | Comments (0)

Thought I would share a quick tip today for managing database connections and debug information betwen your local development machine and production server.

Personally I tend to have a version running on my local development machine and on my web server and keep them in synch using the excellent Aptana Studio IDE and the following mean that I can do this without worrying about overwriting my database settings whenever I synchronise.

For starters replace the DATABASE_CONFIG class in APP/config/database.php with the code below, substituting your database login details where applicable:

<?php
class DATABASE_CONFIG {
    var $development = array(
        'driver' => 'mysql',
        'persistent' => false,
        'host' => 'localhost',
        'port' => '',
        'login' => 'your_local_username',
        'password' => 'your_local_password',
        'database' => 'your_local_database',
        'schema' => '',
        'prefix' => '',
        'encoding' => ''
    );
    var $production = array(
        'driver' => 'mysql',
        'persistent' => false,
        'host' => 'your_remote_server',
        'port' => '',
        'login' => 'your_remote_username',
        'password' => 'your_remote_password',
        'database' => 'your_remote_database',
        'schema' => '',
        'prefix' => '',
        'encoding' => ''
    );
    var $default = array();
    function __construct(){
        $this->default = ($_SERVER['SERVER_ADDR'] == '127.0.0.1') ? $this->development : $this->production;
        }
    function DATABASE_CONFIG(){
        $this-> __construct();
    } 
}
?>

This will automatically set the correct database to use according to the server your application is running on, next replace the line that reads:

    Configure::write('debug', 2);

in APP/config/core.php with the following:

if($_SERVER['SERVER_ADDR'] == '127.0.0.1'){
        Configure::write('debug', 2);
    }else{
        Configure::write('debug', 0);
    }

This effectively does exactly the same with your debug setting, so that on your development machine you will get debugging information, but not on your production set up.

Anyway, just thought I'd share, I tend to make these changes automatically at the beginning of every project and find them to be incredibly usefull.

'till the next time

...happy baking

Have your say:





Please enter the code