fbrandel fbrandel - 1 year ago 206
YAML Question

How to use a YAML config file in Silex Framework

Is it possible to configure a Silex Application with YAML config files? I bet yes, but how is it done correctly? For instance I want to use different configurations according to the environment, like config.dev.yml and config.prod.yml.

The config file should contain parameters for the app itself and for the registered extensions/services.


// Debug flag should be set in the config file
$app['debug'] = true;

// Extension options should also be set in config file
$app->register(new Silex\Extension\TwigExtension(), array(
'twig.path' => __DIR__.'/views',
'twig.class_path' => __DIR__.'/vendor/Twig/lib',

Do I have to parse the YAML file by myself and set the parameters accordingly or is there a more "magic" way to do this?

Answer Source

First of all, add the Symfony Yaml component to your composer.json

"symfony/yaml": "2.1.*@dev",

Use the right version choosing directly from the packagist page: https://packagist.org/packages/symfony/yaml

Now, you can add the deralex YamlConfigProvider, a simple and useful Silex provider. Add it to your composer.json:

"deralex/yaml-config-service-provider": "1.0.x-dev"

Here the official github page: https://github.com/deralex/YamlConfigServiceProvider

Here the packagist page: https://packagist.org/packages/deralex/yaml-config-service-provider


Install the dependencies with ./composer.phar update command and finally add these lines to your app file:

$app = new Silex\Application();
$app->register(new DerAlex\Silex\YamlConfigServiceProvider(__DIR__ . '/settings.yml'));

Now, for example, you can do this:


    driver: pdo_mysql
    host: localhost
    dbname: database_name
    user: root
    password: password
    charset: utf8


$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
    'db.options' => $app['config']['database']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download