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!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Smaine Milianni

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