How to Work with Compiler Passes in Bundles

How to Work with Compiler Passes in Bundles

Compiler passes give you an opportunity to manipulate other service definitions that have been registered with the service container. You can read about how to create them in the components section "Execute Code During Compilation".

When using separate compiler passes, you need to register them in the build() method of the bundle class (this is not needed when implementing the process() method in the extension):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// src/AppBundle/AppBundle.php
namespace AppBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use AppBundle\DependencyInjection\Compiler\CustomPass;

class AppBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new CustomPass());
    }
}

One of the most common use-cases of compiler passes is to work with tagged services (read more about tags in the components section "Working with Tagged Services"). If you are using custom tags in a bundle then by convention, tag names consist of the name of the bundle (lowercase, underscores as separators), followed by a dot and finally the "real" name. For example, if you want to introduce some sort of "mail_transport" tag in your AppBundle, you should call it app.mail_transport.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.