Switching from live, beta, and local databases.

Since I keep my server in sync with my local files, I wanted a way to switch from my server and localhost database connection. I found a way to achieve this here ( Multiple Domains with one entry script ) but I didn’t like the fact that I had to add multiple config files.

So here was my solution to switching from multiple database entries.

protected/config/main.php




'components' => array(


...


'db' => require(dirname(__FILE__) . '/dbconnect.php'),


...


);



create: protected/config/dbconnect.php




$hostname = $_SERVER['SERVER_NAME'];

switch (strtolower($hostname)) {

    case 'example.com';

    case 'www.example.com';

        return array(

            'connectionString' => 'mysql:host=localhost;dbname=myYiiDB',

            'emulatePrepare' => true,

            'username' => 'USER_HERE',

            'password' => 'PASS_HERE',

            'charset' => 'utf8',

        );

        break;


    case 'beta.example.com';        

        return array(            

            'connectionString' => 'mysql:host=localhost;dbname=myYiiDB',            

            'emulatePrepare' => true,            

            'username' => 'USER_HERE',            

            'password' => 'PASS_HERE',           

            'charset' => 'utf8',        

    );        

    break;


    default:

        return array(

            'connectionString' => 'mysql:host=localhost;dbname=myYiiDB',

            'emulatePrepare' => true,

            'username' => 'root',

            'password' => '',

            'charset' => 'utf8',

        );

}



Maybe there is a better solution for this if so please share :)