Programmatically set environment for Symfony project

I have recently been working on a web project built on Symfony 1.4. There are a team of developers, each has their own installation and we had the problem whereby each needed their own particular configuration settings. Symfony allows for multiple configurations to be specified using “environments” but the problem is how to get each installation to choose the correct environment without changing index.php – which of course would affect everyone else each time it was committed to Subversion.

The solution was to create a simple class that looks for the existence of a file, environment.cfg, in the configuration directory. The contents of the file specify which environment to use. This file is not committed to Subversion each developer can specify their own environment without affecting anything in Subversion.

We added a few lines to our index.php file like this:

// Load the class which chooses the environment

// Instantiate the class - specify the default environment to "live" (if there is no environment.cfg file)
$environment = new ApplicationEnvironment("live");

// Try and read environment.cfg

// Create a configuration object using the chosen environment
$configuration = ProjectConfiguration::getApplicationConfiguration('frontend', $environment->getEnvironment(), $environment->getDebugMode());

Note that the debug mode option is also set by the ApplicationEnvironment object. This is determined by the URL:

// in ApplicationEnvironment.class.php
    public function getDebugMode()
        $debugAddresses = array("");
        return in_array($_SERVER['SERVER_NAME'], $debugAddresses);

We could have used the environment.cfg file to specify this, for example on another line, but we also needed to specify debug mode on our live server so that if the site is accessed at it is not in debug mode, but if it is accessed via then it is in debug mode (of course is http password protected).


Next we had the problem of setting the environment. We could of course rely on each developer to put --env=my-environment but it would be much nicer to have this done automatically. The solution was to create a simple script that resides in the application root directory next to symfony.php that looks something like this:


$environment = new ApplicationEnvironment("live");

$envSet = false;

foreach ($argv as $i => $arg)
    if (substr($arg, 0, 6) == "--env=")
        $envSet = true;

if (!$envSet)
    $argv[] = sprintf("--env=%s", $environment->getEnvironment());

    $_SERVER['argv'] = $argv;
    $_SERVER['argc'] = $argc;


It’s a bit of a nasty mess, but it works at least.



This entry was posted in PHP and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *