When you build an application, it is often deployed to a number of servers each with a different set of configurations. The development and production servers, with different debug, logging, and database details is an obvious example. Many approaches I have seen to dealing with this, including Anis uddin Ahmad’s post that inspired this one, involve determining the domain the application is running on, and loading a pre-determined configuration for that host.
There are 2 downfalls to that solution from my point of view;
Each new environment involves editing the source of the application
If the application involves command line components, there is no way to determine the domain, requiring a special case
My solution may look familiar if you have ever looked at python’s django. It involves using environment variables, which can be set through the web server, or on the command line – even in crontab. Basically, I set an environment variable specifying the location of the configuration file to load into the application. I actually allow a list of configuration files,so you can have a “base” and only override specific configuration as required per location.
To add and environment variable in apache, you use the mod_env module’s SetEnv directive.
SetEnv APPLICATION_CONFIG /path/to/config/basic.php:/path/to/config/development.php
on the command line, you can use export.
and very similarly in crontab (above the code that requires it)
To read the configuration files, from php we can simple get the environment variable with getenv(), then merge each configuration into the applications configuration;
1 2 3 4 5 6 7 8 9 10
In this example I am using simple PHP files to store the configuration arrays, you could also use any other format Zend_Config can read. You could also use a simple array and array_merge() instead on Zend_Config if you are not using the framework.