0

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'
Andrei Herford
  • 17,570
  • 19
  • 91
  • 225
  • 2
    use controller injection: https://symfony.com/doc/current/service_container.html#fetching-and-using-services – craigh Jun 02 '22 at 11:39
  • @craigh That would be possible of course. However, I would like to keep the controller flexible and use the same controller for different routes. Each route should be handled differently based on the used parameters / service – Andrei Herford Jun 02 '22 at 12:02
  • Interesting that parameters worked but services did not. I would not have expected parameters to work. I assume you double checked that the service did not work. Might take a look at the code. Maybe there is a way to convince it to use the service. Bit dubious of your example since the RedirectController does not use the logger directly. I suppose you could make a [LoggerServiceLocator](https://symfony.com/doc/current/service_container/service_subscribers_locators.html) and inject it instead of the complete container. But I think you might be over engineering a bit. – Cerad Jun 02 '22 at 13:57

0 Answers0