The Symfony Compiler Pass š„
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 theaddDebugger
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!