The Symfony Compiler Pass 🔥

Smaine Milianni
2 min readDec 4, 2020

--

(Version Française)

One of the most powerful features of Symfony is the service container and the dependency injection, it allows us to deal with services definition in many ways and help us to solve some complex problems in an easy way…

In this article, I’ll show how you can deal with service definition at the runtime 🚀

Our use case is simple we have an application in many countries, each country has specific parameters but they have the same base code, and depends on where the application is deployed we want a specific debug.

In the French Context, we have 2 debuggers and in the Uk Context, we have one debugger, when we need to debug wewant to iterate on all available debuggers.

1. Create the ChainDebugger 🔗

The ChainDebugger is the end class that we call to debug, its job is to iterate on all available debuggers and call the debug method.

2. Create All Debuggers 🥖

I will create 3 debuggers, Two for the French context and one for the Uk context, all of them should implement an interface, that force them to have a contract and it allows us to say to Symfony “Hey give me all services with this interface”

3. Service definition ✏️

After creating the classes we should add a tag for each service to be able to fetch them by tag

4. Compiler Pass 💡

At this point, we have a ChainDebugger and we have 3 debuggers, the mission is to add our debuggers in the ChainDebugger but we don’t want to add all debuggers, we want DebuggerForFrenchContext and DebuggerCheeseForFrenchContext for the French context and DebbugerForUKContext for the UK context.

Each application has a parameter context in the config but it can be an env variable or something in the database… That doesn’t matter here.

What we will do:

  • Fetch the context (can be “fr” or “uk”)
  • Fetch ChainDebbuger from the container
  • Fetch all available Debuggers with the tag (‘app.custom_debug_fr’ or ‘app.custom_debug_uk’)
  • Add each Debugger in ChainDebbuger with the addDebugger method
  • Tell to Symfony to register this CompilerPass

5. Use it 🎉

That’s all,

I hope you enjoyed it, don’t forget to clap it and to share it!

--

--

Smaine Milianni

Fullstack Developer- certified Symfony 4,5 and certified AWS Solution Architect - Freelancer - Remote Worker