Simple Environments In Silex

Setting machine-specific configuration (database credentials, etc.) as environment variables allows easier managment of configuration. Plus, you won't ever again commit sensitive information in your git history.

Here is the basic workflow to created a Silex application

composer create-project fabpot/Silex-Skeleton myapp
cd myapp
git init
git add .
git commit -am "Initial commit"

But that means that your database configuration (and other config keys) is in your git repository. It makes it complicated to switch between dev and prod parameters. Also, you probably don't want to have your production passwords in the git repository. A neat workaround is to use environment variables.

Set the environment variables

You set those in your web server. If you use Apache, you declare them in the VirtualHost section.

<VirtualHost *:80>
    SetEnv MYAPP_DATABASE_USER qpleple
    SetEnv MYAPP_DATABASE_PASSWORD mySuperPassword

If you use Nginx, declare them in the Nginx config file.

fastcgi_param MYAPP_DB_USER qpleple
fastcgi_param MMYAPP_DB_PASSWORD mySuperPassword

Get them in Silex

Then, in your Silex app, you can just read those value. Don't forget to have default values (like in the example) in case the environment variables are not set.

$app['debug'] = getenv('MYAPP_DEBUG') == 'true' ?: false;

$app['db.options'] = array(
  'driver'   => 'pdo_mysql',
  'dbname'   => getenv('MYAPP_DB_DBNAME')   ?: 'myapp',
  'host'     => getenv('MYAPP_DB_HOST')     ?: 'localhost',
  'user'     => getenv('MYAPP_DB_USER')     ?: 'root',
  'password' => getenv('MYAPP_DB_PASSWORD') ?: '',
Quentin Pleplé
March 2013