I am working with Symfony 6
. The configuration of a route allows to add extra parameters which are passed to the controller:
index:
path: /somepage
controller: App\Controller\PageController::index
defaults:
title: 'Hello world!'
Is it possible to use a service as parameter? Something like:
defaults:
foo: '%some.container.parameter%' << Works, use container parameter?
logger: '@logger' << FAILS, use services as parameter?
This example does not work. While container parameters are correctly resolved, the services parameter is interpreted as string @logger
instead of being resolved to the logger service.
Of course one could inject the complete service container into the PageController
and use $this->container->get($logger);
to get the services by its id. However, I found several sources, that injecting the services container is a bad idea which should be avoided.
So, is it possible to use a services as routing parameter?
Background
I would like to use a service parameter to make the controller more flexible when being used at different places.
For example the RedirectController
can be used to create simple redirects without having to create a different controller for each redirected route.
Assume that the redirection of some routes is critical for some reason and needs more verbose logging and for example an alert notification via email.
Instead of creating different controllers and injecting different loggers, one could solve this by using different loggers as parameter:
legacy_one:
path: /somepage
controller: Symfony\Bundle\FrameworkBundle\Controller\RedirectController
defaults:
logger: '@defaultLogger'
legacy_two:
path: /otherpage
controller: Symfony\Bundle\FrameworkBundle\Controller\RedirectController
defaults:
logger: '@alertLogger'