Configuring Yii to run on both Windows and OSX

If you develop your Yii project on both Windows and Mac, there can be a problem setting up the configuration unless the configurations for both system are identical. On my machines I have the following configurations:

Mac: MAMP with the default port settings (8888 for Apache and 8889 for MySQL).

Windows: Apache is configured to use port 80 and MySQL to port 3306.

To handle these differences, I have modified index.php like this:

<?php

$yii = dirname(__FILE__) . '/framework/yii.php';

if (substr_compare($_SERVER['HTTP_HOST'], 'localhost', 0, 8) === 0){
    if ($_SERVER['HTTP_HOST'] == 'localhost') {
        $config = dirname(__FILE__) . '/protected/config/development_win.php';
    } else {
        $config = dirname(__FILE__) . '/protected/config/development_osx.php';
    }
    defined('YII_DEBUG') or define('YII_DEBUG', true);
    defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', 3);
} else {
    $config = dirname(__FILE__) . '/protected/config/production.php';
}
require_once($yii);
$app = Yii::createWebApplication($config);
$app->run();

You then need three configuration files – one for the production environment, one for Windows and one for OSX.

That’s it.

Tip

To further enhance the configuration files, you can keep the common configuration items in /protected/config/main.php and merge it in from the three config files. Here’s an example:

<?php
return CMap::mergeArray(
    require(dirname(__FILE__) . '/main.php'),
    array(
        'preload'=>array(
            //'log',
        ),
        'modules' => array(
            'gii' => array(
                'class' => 'system.gii.GiiModule',
                'password' => false,
                // If removed, Gii defaults to localhost only. Edit carefully to taste.
                'ipFilters' => array('127.0.0.1', '::1'),
            ),
        ),
        'components' => array(
            'db' => array(
                'tablePrefix' => 'tbl_',
                'connectionString' => 'mysql:host=localhost;dbname=mydatabase',
                'emulatePrepare' => true,
                'enableParamLogging' => true,
                'username' => 'me',
                'password' => 'supersecret',
                'charset' => 'utf8',
            ),
        ),
    )
);

Enjoy.

1 0
4 followers
Viewed: 6 786 times
Version: 1.1
Category: How-tos
Tags: config
Written by: trond
Last updated by: CeBe
Created on: Feb 13, 2014
Last updated: 4 years ago
Update Article

Revisions

View all history

Related Articles