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: http://symfony.com/doc/current/book/service_container.html

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'));
        $loader->load('services.yml');
    }

    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

3 comments:

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

    ReplyDelete
  2. Hi!

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

    Thanks!

    ReplyDelete