Enhanced Foolproof Multi-environment Config

Problem

This code snippet supports dynamic environment configuration using either the APP_ENV environment variable, or “Laravel-style” server name resolution as a fallback.

Solution

Place the following code at the top of your public/index.php file:

<?php

define('CRAFT_ENVIRONMENT', call_user_func_array(function($a,$b){if(array_key_exists('APP_ENV',$_SERVER)&&in_array($c=$_SERVER['APP_ENV'],array_keys($a))){return $c;}foreach($a as $c=>$d){$e=$_SERVER['SERVER_NAME'];if((is_array($d)&&in_array($e,$d))||$e==$d){return $c;}}return $b;}, array(

    // Environment Definitions
    array(
        'local'   => array('local.project.com'),
        'dev'     => array('dev.project.com'),
        'staging' => array('staging.project.com'),
    ),

    // Default Environment
    'production',

)));

(You can find the expanded version here.)

You’ll then be able to configure either craft/config/general.php or craft/config/db.php as follows:

<?php

return array(
    '*' => array(
        //
    ),
    'local' => array(
        //
    ),
    'dev' => array(
        //
    ),
    'staging' => array(
        //
    ),
    'production' => array(
        //
    ),
);

Hope that helps!