Yii Framework Separate Configurations for Different Environments

Yii doesn’t have a built-in way of changing configurations based on the environment that it is running in. However, there are a number of ways to accomplish this.

Method #1

There is a great extension available that allows you to use different configuration files based on the environment that is found in the Apache configuration file.  Yii-environment does require modification of these files, so the most basic hosting plan may not be able to accommodate the extension.  However, as is true with any programming task, there is more than one way to skin a cat.

Method #2

Another method for differentiating environments is to edit the index.php file. Based on a PHP server variable, a different configuration file can be used.

switch ($_SERVER['SERVER_NAME']) {
    case "development":
        $config=dirname(__FILE__).'/protected/config/development.php';
        break;
    default:
        $config=dirname(__FILE__).'/protected/config/production.php';
        break;
}

To make things easier, you can just include the variables that will differ in your development/production configuration files. A third file can be used to hold all shared variables. For instance, your shared configuration file can look like:

return array(
    'basePath' => dirname(__FILE__) . DIRECTORY_SEPARATOR . '..',
    'name' => 'Application Name',
    // autoloading model and component classes
    'import' => array(
        'application.models.*',
        'application.components.*',
    ),
    // application components
    'components' => array(
        'user' => array(
            // enable cookie-based authentication
            'allowAutoLogin' => false,
        ),
   ),
);

Then, each of the environment-specific variables can go into the development or production.php configuration files.

return CMap::mergeArray(
        require(dirname(__FILE__) . '/shared.php'),
        array(
            'components' => array(
                'db' => array(
                    'connectionString' => 'mysql:host=mysql;dbname=databaseName',
                    'emulatePrepare' => true,
                    'username' => 'user',
                    'password' => 'password',
                    'charset' => 'utf8',
                ),
            ),
     )
);
Share this page:
  • Facebook
  • Twitter
  • Reddit
  • Google Bookmarks
  • email
  • Print
  • RSS
  • Digg
  • StumbleUpon
  • del.icio.us
  • Slashdot
  • Technorati
  • Tumblr

Steven Michaels

Steven Michaels specializes in PHP web applications utilizing MediaWiki, WordPress, Yii Framework and others. He is an open source contributor and leads development for both of Hollow Developers' internal projects, HollowGame and SpeechEase.

Facebook comments:

Leave a Reply