11

Can someone explain what a compilerpass is?

j0k
  • 22,600
  • 28
  • 79
  • 90
flyboarder
  • 586
  • 1
  • 5
  • 21

1 Answers1

25

CompilerPass implementations are some kind of listeners that are executed after dependency injection container is built from configuration files and before it is saved as plain PHP in cache. They are used to build some structures that requires access to definitions from outer resources or need some programming that is not available in XML/YAML configuration. You can consider them as "final filters" that can modify entire DIC.

Let's consider a TwigBundle and its TwigEnvironmentPass. What it does is quite simple:

  1. Fetch a reference to twig service (defined as <service id="twig" class="..." ...>)
  2. Find all services that has been tagged with twig.extension tag. To do that you have work on complete DIC (built from XML configuration files) as those services might be defined in any bundle.
  3. Build a custom code for service creation method.

As a final result the following code will be generated:

protected function getTwigService()
{
    $this->services['twig'] = $instance = new \Twig_Environment($this->get('twig.loader'), ...);

    // THIS HAS BEEN ADDED THANKS TO THE TwigEnvironmentPass:
    $instance->addExtension(new \Symfony\Bundle\SecurityBundle\Twig\Extension\SecurityExtension($this->get('security.context')));
    $instance->addExtension(new \Symfony\Bundle\TwigBundle\Extension\TransExtension($this->get('translator')));
    $instance->addExtension(new \Symfony\Bundle\TwigBundle\Extension\TemplatingExtension($this));
    $instance->addExtension(new \Symfony\Bundle\TwigBundle\Extension\FormExtension(array(0 => 'TwigBundle::form.html.twig', 1 => 'SiteBundle::widgets.html.twig')));
    $instance->addExtension(new \MyProject\SiteBundle\Twig\Extension\MyVeryOwnExtensionToTwig($this));

    return $instance;
}
Crozin
  • 43,890
  • 13
  • 88
  • 135