简体   繁体   中英

How can I access the container in a before kernel listener in Symfony2?

I try to implement a before kernel listener ( see reference ) where I simply set some parameter values (that I have to fetch dynamically and cannot statically declare in my parameters.yml file).

This is my listener class:

class AcmeListener
{
    public function onKernelController(FilterControllerEvent $event)
    {
        $event->getController()->getContainer()->setParameter('foo', 'bar');
    }
}

And in my config.yml :

services:
    kernel.listener.acme_listener:
        class: Acme\AcmeBundle\EventListener\AcmeListener
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

But I get a

FatalErrorException: Error: Call to a member function getContainer() on a non-object

How can I access the container, if not via getContainer() from the $event->getController() ?

Just add the container as an argument into your service definition.

services:
    kernel.listener.acme_listener:
        class: Acme\AcmeBundle\EventListener\AcmeListener
        arguments:
            - @service_container
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

Then add a constructor to your AcmeListener class so you can access it.

use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

class AcmeListener
{
    /**
     * @var Container
     */
    private $container;

    /**
     * Constructor
     *
     * @param Container $container
     */
    public function __construct(Container $container)
    {
            $this->container = $container;
    }

    public function onKernelController(FilterControllerEvent $event)
    {
            $this->container->...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM