Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 explanation of CompilerPass?

Can someone explain what a compilerpass is?

like image 705
flyboarder Avatar asked Jun 24 '11 22:06

flyboarder


People also ask

What are compiler passes in C++?

Compiler passes are registered in the build () method of the application kernel: One of the most common use-cases of compiler passes is to work with tagged services. In those cases, instead of creating a compiler pass, you can make the kernel implement CompilerPassInterface and process the services inside the process () method:

What license does Symfony use?

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license. Symfony 6.0 is backed by SensioLabs . Peruse our complete Symfony & PHP solutions catalog for your web development needs.

How do I define a compiler pass in a bundle?

Bundles can define compiler passes in the build () method of the main bundle class (this is not needed when implementing the process () method in the extension):


1 Answers

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;
}
like image 182
Crozin Avatar answered Sep 27 '22 19:09

Crozin