It passed about half year since I scratched Symfony2 Framework surface. Basics are behind me, now it’s time for middle-level stuff. I’m excited to start a whole new Symfony related blog post series. I didn’t wanted to copy typical tutorial topics. It would be waste of your time and my work. I thought it would be nice to show some code related to Symfony Dependency Injection Container.
Tutorials usually show typical container services definition. Boring stuff. I’m going to show you dynamic collection of services passed into processor service. The idea is that collection doesn’t know its elements, so every bundle can define its own services to be added to collection. The secret is tags. To add some spice, tagged service can be defined with priority. And we can specify that this processor should be run at the beginning, and that at the end.
We’ll start with defining common processor interface and some basic implementations.
Now it’s time for a service that processes given argument with all the processors one by one.
We could define typical container definitions and pass processors right into processing service, but remember about requirement that external bundles can define their own processors. We’ll use tags.
Now the key part: compiler pass definition.
At the first sight you may think that it’s a lot of logic to run to define stupid processor. What about performance? No worries. Remember, the compilation outcome is dumped into cache file on prod environment. All these foreach loops and priority queues are being run only once.
Solution is pretty generic, you can easily adapt to your own needs. Of course code is on MIT license, so grab it and use in your own (even commercial) projects!
Happy PHP container compiling :-)