Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 62 ยท Services and the Container

Compiler Passes and Bundle Extensions

Understand how Symfony compiles the container, write a compiler pass and a bundle extension, and structure a reusable bundle with AbstractBundle and a config tree.

Everything you have configured so far, services, aliases, tags, parameters, is collected first and used later. Between those two moments Symfony runs a compilation step that validates the configuration, resolves autowiring, removes unused services and finally dumps optimized PHP code into var/cache/. Most of the time you never touch this phase. When you build a reusable library, or need to change service definitions based on what other services exist, you hook into it with a compiler pass or a bundle extension.

This lesson explains the compilation phases, shows the two extension points with real Symfony code (read-only) and gives you two runnable stand-ins: a mini container builder with a compiler pass, and a configuration-merging extension. It ends with the layout of a small reusable bundle.

What happens when the container compiles

The container you use at runtime is generated code. The object that produces it is the ContainerBuilder, which holds definitions (a recipe for each service: class, arguments, tags), not instances. Compilation processes those definitions in stages:

  1. Load: your services.yaml, the files in config/packages/ and every bundle's extension add definitions and parameters.
  2. Merge and resolve: the extensions' output is merged and parameters are resolved.
  3. Compiler passes: a long list of passes runs, one after another. Built-in ones resolve autowiring, process tags, check arguments, inline small services and remove unused private ones.
  4. Dump: the final definitions are written as plain PHP in var/cache/<env>/.

At runtime, requests only load the dumped PHP file. This is why changing a service definition has no cost for visitors, and why many wiring errors appear when you run cache:clear instead of in the middle of a request.

flowchart LR
    L["Load configuration<br/>services.yaml, config/packages"] --> E["Bundle extensions<br/>add definitions"]
    E --> P["Compiler passes<br/>autowire, tags, remove unused"]
    P --> D["Dump optimized PHP<br/>var/cache"]
    D --> R["Runtime: requests load the dumped container"]

Definitions are collected, transformed by compiler passes, and dumped once; requests only run the result.

Compiler passes

A compiler pass is a class with one method that receives the ContainerBuilder and may read or change any definition. The classic use is to find all services with a certain tag and wire them into a collector, which is what #[AutowireIterator] does for you in simple cases. A hand-written pass is useful when you need more control: validate tags, change a definition's class or reorder things.

PHP
<?php
namespace App\DependencyInjection\Compiler;

use App\Export\ReportExporter;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

final class FormatterPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        if (!$container->has(ReportExporter::class)) {
            return;
        }

        $exporter = $container->findDefinition(ReportExporter::class);

        foreach ($container->findTaggedServiceIds('app.formatter') as $id => $tags) {
            foreach ($tags as $attributes) {
                $exporter->addMethodCall('addFormatter', [
                    new Reference($id),
                    $attributes['format'] ?? throw new \LogicException(
                        sprintf('Service "%s" needs a "format" attribute on its app.formatter tag.', $id)
                    ),
                ]);
            }
        }
    }
}

You register it in the application's kernel:

PHP
<?php
// src/Kernel.php
namespace App;

use App\DependencyInjection\Compiler\FormatterPass;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;

class Kernel extends BaseKernel
{
    use MicroKernelTrait;

    protected function build(ContainerBuilder $container): void
    {
        $container->addCompilerPass(new FormatterPass());
    }
}

By default a pass runs before optimization, which is the right moment for passes that read tags and add method calls. A second argument selects another phase (PassConfig::TYPE_OPTIMIZE, TYPE_BEFORE_REMOVING, TYPE_REMOVE, TYPE_AFTER_REMOVING) when you need to run after autowiring or after unused services were removed.

A pass works with definitions, never with real objects: you can say "call addFormatter with a reference to service X", but you cannot call a method on service X yourself, because it does not exist yet.

PHP A mini container with a compiler pass (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Two things to notice: the pass runs once, before any service is used, and a mistake in tag attributes fails at compile time with a message about the faulty service. That is the practical benefit of putting wiring logic in a pass rather than in runtime code.

Bundle extensions

A bundle is a package that plugs into the kernel and can bring services, configuration, routes and templates. The part that adds services is its extension. When the container loads, each bundle's extension receives the configuration written under its alias (for example acme_greeting: in config/packages/acme_greeting.yaml), validates and merges it, then registers service definitions.

Since Symfony 6.1 the easiest way to write a bundle is to extend AbstractBundle, which puts the config definition and the service loading in one class:

PHP
<?php
namespace Acme\GreetingBundle;

use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\HttpKernel\Bundle\AbstractBundle;

final class AcmeGreetingBundle extends AbstractBundle
{
    public function configure(DefinitionConfigurator $definition): void
    {
        $definition->rootNode()
            ->children()
                ->scalarNode('greeting')->defaultValue('Hello')->end()
                ->booleanNode('shout')->defaultFalse()->end()
            ->end();
    }

    /** @param array{greeting: string, shout: bool} $config */
    public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void
    {
        $container->import('../config/services.php');

        $container->services()
            ->get('acme_greeting.greeter')
            ->arg('$greeting', $config['greeting'])
            ->arg('$shout', $config['shout']);
    }
}

The bundle's config/services.php defines the acme_greeting.greeter service. Users of the bundle then write only:

YAML
# config/packages/acme_greeting.yaml
acme_greeting:
    greeting: 'Welcome'
    shout: true

You register the bundle in config/bundles.php (Flex does it automatically when the package ships a recipe):

PHP
<?php
return [
    // ...
    Acme\GreetingBundle\AcmeGreetingBundle::class => ['all' => true],
];

The bundle class can also override build(ContainerBuilder $container) to register compiler passes, and prependExtension() to set defaults for other bundles (for example, configuring Twig paths).

The older style, still common in existing bundles, is a separate DependencyInjection/AcmeGreetingExtension.php class that implements load(array $configs, ContainerBuilder $container) plus a Configuration class with getConfigTreeBuilder(). The ideas are the same; AbstractBundle just removes the boilerplate.

The configuration tree

Notice what the configure() method does: it declares the allowed keys, their types and defaults. Symfony then validates whatever users write: an unknown key or a wrong type is an error with a clear path, such as Unrecognized option "greting" under "acme_greeting". If several config files set the same option (for example config/packages/acme_greeting.yaml and an environment-specific override), Symfony merges them before loadExtension() runs, so the method receives one clean array.

PHP A config tree and extension (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first case shows defaults, the second shows two config files merged into one array, and the last two show the validation errors that protect users of a bundle from silent typos.

Compiler pass or extension?

  • Use an extension (or AbstractBundle::loadExtension) to add services and turn user configuration into definitions.
  • Use a compiler pass to adjust definitions once all bundles and your own code have contributed, for example to collect tagged services.
  • For simple collections, a tag with #[AutowireIterator] is enough: no pass required.

Reach for these tools rarely in application code. They matter most when you publish a bundle or when you need a rule that applies across the whole container.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a compiler pass operate on?

    Passes read and modify definitions (class, arguments, tags). The services themselves do not exist yet when a pass runs.
  2. 2. Why does compilation matter for performance?

    The dumped container is ordinary PHP code that creates services directly, so all wiring work happens once, at build time.
  3. 3. Where do the values a user writes under acme_greeting: in config/packages/ end up?

    The bundle's configuration tree validates and merges them, and the extension (loadExtension in AbstractBundle) receives the result.
  4. 4. Which is the best fit for registering a new compiler pass in an application?

    The kernel's build() method (or a bundle's build()) is where passes are added to the ContainerBuilder.

Summary

  • The container is compiled: definitions are loaded, merged, transformed by compiler passes and dumped as optimized PHP.
  • A compiler pass implements CompilerPassInterface::process() and edits definitions; register it in Kernel::build() or in a bundle's build().
  • A bundle extension validates user configuration through a config tree and turns it into service definitions; AbstractBundle combines both in one class.
  • Prefer tags with #[AutowireIterator] for simple collections; use passes and extensions for cross-cutting rules and reusable packages.
  • The runnable examples here are stand-ins, but the vocabulary (definition, tag, pass, extension, config tree) is the real one.

Next, move on to application settings per environment in Configuration and Environments.