Symfony2: How to get configuration parameter in listener?

I have a listening service. I want to read some configuration options inside it.

How can I access the service container in the listener class?

+7
source share
2 answers

You can pass the container parameters to your service using the notation %your_param_name% :

 services: kernel.listener.locale_listener: class: My\BundleName\Listener\LocaleListener tags: - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest } arguments: [ @router, @service_container, %your_param_name% ] 

which will present as an example (in this example) the third argument in the service constructor method:

 public function __construct($router, $container, $paramValue) { // ... } 
+25
source

Solved: we need to pass @service_container itself as an argument to the listener service

MyBundleName / Resources / services.yml

 services: kernel.listener.locale_listener: class: My\BundleName\Listener\LocaleListener tags: - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest } arguments: [ @service_container ] 

Listener Class:

 class LocaleListener { protected $container; public function __construct(\Symfony\Component\DependencyInjection\Container $container) { $this->container = $container; } .. public function Myfunction() { $languages = $this->container->getParameter('languages'); } } 
-one
source

All Articles