May 10
11
Working with multiple environments
Hi Guys,
I have been recently been working on a few complex web development projects which mainly require me to use multiple environments within the development cycle, mainly these are: Development, Staging, Live.
While it wouldn’t be too difficult to manually set an environment variable this caused its own problems in the long run and across multiple developers who are working on the same project within the same development box.
While i was working on one of the project i setup my local development environment and i decided to use a non-web accessible domain name using my local hosts file to bypass my ISP’s and any local DNS setup.
i setup my local hosts file in the format of:
127.0.0.1 project_name.client.dev
While this name convention doesn’t appear to be important it will all be clear when i show the code later on in this post.
To show my clients their site in a “live” environment i setup a sub-domain on my server of dev.zenmedia.co.uk. This will be used as my staging environment and the site name convention will follow that of the local development environment.
When i setup the config.php file i use multiple configuration instances within the same document, this will allow for a single point of setup for any of the three development environments.
// This is where the environment is checked and acted upon
// dev server
if(stristr($_SERVER['HTTP_HOST'],'.dev')){
error_reporting(E_ALL);
define("SQL_USER", 'dev_user');
define("SQL_PASSWORD", 'dev_pass');
define("SQL_DB", 'dev_db');
define("SQL_SERVER", 'localhost');
}
// staging server
elseif(stristr($_SERVER['HTTP_HOST'],'.dev.zenmedia.co.uk')){
ini_set('display_errors',0);
error_reporting(E_ALL);
define("SQL_USER", 'staging_user');
define("SQL_PASSWORD", 'staging_pass');
define("SQL_DB", 'staging_db');
define("SQL_SERVER", 'localhost');
}
// live server
else{
ini_set('display_errors',0);
error_reporting(E_ALL);
define("SQL_USER", 'live_user');
define("SQL_PASSWORD", 'live_pass');
define("SQL_DB", 'live_db');
define("SQL_SERVER", 'localhost');
}
While this appears to be a little overkill in relation to assignment of variables it allows ALL developers a single point of reference for db connection variables.
While i can guess many of you are wondering, “why didn’t you use a switch?” the reason for this is simple. There currently isn’t a reasonable method to allow for part $_SERVER['HTTP_HOST'] domain name matching, in addition to this while a switch is visually easier to read, i choose function over form.