Let’s say I’ve two services:
get('my_first_service')
get('my_second_service')
I want to do something like this:
$this->get('my_first_service')->doSomething($this->get('my_second_service'));
This is some initialization code that must be active everywhere in the project. As far as I see I have a few options (both services originates from the vendor-dir (haven’t writtem them myself)):
- Add the above code (with some modifications) in app.php and/or app_dev.php
- Add the above code to every controller action
- Create a service with the services as arguments and add the above code in the constructor
The first option seems a little bit “unusual” as I don’t link editing the app.php file for something link this. The second option is too inefficient as I need to do this for dozens of actions. The third action seems better but I still need to call this service from somewhere in order to execute the constructor right?
I have the feeling I’m missing a possibility… there must be a better place for this kind of initialization code right?
If you really want to do execute your code before EVERY action, you can listen for the event kernel.controller.
Check this example in the cookboook.
Your listener is a service so you can inject both of your services if needed.