Easy peasy database config

By Joel Moss (joelmoss)
Like a lot of developers out there, I use Subversion to keep control of my code and projects, and I also use a different database for development and production. But when using Cake this can be a problem when checking out my code from development to production. Unless I edit my database.php with my production config, the production code would have problems, as it would be trying to access data from the development database.

What I needed was an easy-peasy way of being able to check in my code to production without having to edit the database.php config file. So what I did was very simple and can be found below.

For a full write up of this trick and other Cake stuff, please see my Blog at http://joelmoss.info
Download code class DATABASE_CONFIG {

    var $development = array(
        'driver' => 'mysql',
        'connect' => 'mysql_connect',
        'host' => 'localhost',
        'login' => 'user',
        'password' => 'passwd',
        'database' => 'app_devel'
    );
    var $production = array(
        'driver' => 'mysql',
        'connect' => 'mysql_connect',
        'host' => 'localhost',
        'login' => 'user',
        'password' => 'passwd',
        'database' => 'app'
    );
    var $test = array(
        'driver' => 'mysql',
        'connect' => 'mysql_connect',
        'host' => 'localhost',
        'login' => 'user',
        'password' => 'passwd',
        'database' => 'app_test'
    );
    var $default = array();

    function __construct()
    {
        $this->default = ($_SERVER['SERVER_ADDR'] == '127.0.0.1') ?
            $this->development : $this->production;
    }
    function DATABASE_CONFIG()
    {
        $this->__construct();
    }
}

 

Comments 160

CakePHP Team Comments Author Comments
 

Comment

1 Why didnt I think of that .

Pretty cool, but ... that's what svn:ignore is for :p
Posted Jan 17, 2007 by Yuka Poppe
 

Comment

2 Just what I needed...

Thanks, I needed an easy way for doing this. Instead of testing using the SERVER_ADDR value, I'm probing the file system for the existence of a file that only resides on the DEV server (outside my app tree so I don't go uploading it accidentally). Within this file, I have DEV-specifig configs.

Unfortunately, I'm repeating this "DEV server check" in /app/webroot/index.php and /app/webroot/test.php and /app/config/database.php because I couldn't figure out a way to set it up so that my whole application AND cake console receive my configuration. Not very DRY.
Posted May 26, 2008 by Brian Warren
 

Comment

3 Or maybe

Or maybe match against the http_host like this:

stristr($_SERVER['HTTP_HOST'],$live_server_url) === false
Where the $live_server_url is, duh, the live server url :)
Posted May 30, 2008 by Andrey Kabakchiev