Loading environment-specific configuration files in CodeIgniter
May 17, 2012
About a year ago, CodeIgniter got the addition of an ENVIRONMENT constant which saved me a lot of headaches with managing difference between my various environments (development, staging, production).
// Conditional I add to index.php to self-determine the environment
if ($_SERVER['SERVER_NAME'] == 'mysite.dev')
{
define('ENVIRONMENT', 'development');
}
else
{
define('ENVIRONMENT', 'production');
}
if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
case 'development':
error_reporting(-1);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
Not only is it great for setting up server configurations like error reporting, it’s perfect for use in config files as well.
// Cloud asset bucket
switch (ENVIRONMENT) {
case 'development':
$config['s3_bucket'] = 'mybucket_develop';
break;
case 'staging':
$config['s3_bucket'] = 'mybucket_staging';
break;
case 'production':
default:
$config['s3_bucket'] = 'mybucket_production';
break;
}
Instead of having to ignore configuration files in Git to handle the differences in production vs. development, now all that is necessary is a conditional to handle the variations.
Fast-forward a year, all the way to yesterday, and I happened upon another great little feature: “Environment-specific configuration files.” It was really by accident that I stumbled on it and only did because I was searching for ENVIRONMENT in my full CI project.
// Is the config file in the environment folder?
if ( ! defined('ENVIRONMENT') OR ! file_exists($file_path = APPPATH.'config/'.ENVIRONMENT.'/config.php'))
{
$file_path = APPPATH.'config/config.php';
}
What! So basically this is telling me that I can have a ‘development’ and ‘production’ folder inside of my ‘application/config’ folder and it will precede the main config.php file. Better yet, it works for all the config files (hooks, constants, routes and even libraries).
I headed to the CI docs and found one paragraph about environment-specific configuration files in the Config class docs. Not exactly prime real estate if you want to get noticed…
Since this was such a surprise to me, I figured it might be helpful to someone else as well. No more conditionals, no more Git ignores. Nice!