Load configurations from custom bundle in Symfony2

Symfony2 configuration file for custom bundleWhen I build apps or add new functionality to Symfony2 I build it into a separate bundle, thus trying to keep the structure modular which is generally a good practice as everyone knows. Keeping all parts of the bundle together makes it easy to maintain and also easy to change the configurations as they reside in same place as the code itself.

In this post I’ll show you how to make Symfony2 core discover your config.yml and services files defined in your custom bundle.

Create new bundle

First let’s create a new bundle that we’ll use as a demo. Run following command in the terminal:

php app/console generate:bundle --namespace=Yysource/Bundle/DemoBundle --no-interaction

Now you should have your bundle generated in similar path to:


Next create a directory called: DependencyInjection in the bundle directory and there create new file called DemoExtension.php. This will hold all of our code that will tell Symfony2 to load the extra config files.

Load the YAML files

# src/Yysource/Bundle/DemoBundle/DependencyInjection/DemoExtension.php
namespace Yysource\Bundle\DemoBundle\DependencyInjection;

 * This is the class that loads and manages your bundle configuration.
class DemoExtension extends Extension
    public function load(array $configs, ContainerBuilder $container)
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));

The code above will load the two specified files “config.yml” and “services.yml” assuming they are in the correct directory which should be:


Handle different environments

You might be wondering what should we do if we want to have different configuration files for different environments. That could be quite handy if you have Sandbox service connection and Production service connection and you want to use one or the other based on your environment variables. That is easy all we have to do is just specify an ENV suffix in the file that we want to load:

// this can load "config_dev.yml" or "config_prod.yml" or any other environment you have specified
$env = $container->getParameter('kernel.environment');
$loader->load('config_'. $env .'.yml');

Use config imports

There is one more option which could be easier but you have less control there. You can accomplished this by referencing it as an import in app/config.yml

   - { resource: "@DemoBundle/Resources/config/config.yml" }
   - { resource: "@DemoBundle/Resources/config/services.yml" }

Just a guy with strong interest in PHP and Web technologies

Tagged with: , , ,

Leave a Reply

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


This site uses Akismet to reduce spam. Learn how your comment data is processed.