Sunday, November 11, 2012

Using services.yml instead of services.xml in Symfony 2

In my application's bundle, I recently wanted to switch from using an XML file to register my services to a YML file. There's more information about services here:

Here's how to do it.

Create the services.yml file in your bundle, probably in something like /src/Acme/DemoBundle/Resources/config/services.yml

Next, edit the bundle's extension file and change which services file gets loaded:

// src/Acme/DemoBundle/DependencyInjection/AcmeDemoExtension.php

namespace Acme\DemoBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\Config\FileLocator;

class AcmeDemoExtension extends Extension
    public function load(array $configs, ContainerBuilder $container)
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));

    public function getAlias()
        return 'acme_demo';

The main changes are:

  1. switching the XmlFileLoader to YamlFileLoader in line 14
  2. canging the file to services.yml in line 15


  1. You also need to change the "use" statement line 6 :
    use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; in
    use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

  2. Hi!

    Why did you decided to migrate from XML to YML definition?
    Aesthetic of the services definition?