Search code examples
symfonysymfony-2.7

Symfony2 Making a Container-Aware Event Dispatcher


I want to set an HTTP Request on the kernel in my Symfony2 application when a custom event is triggered (similar to how Symfony\Component\HttpKernel\Event\GetResponseEvent sets an HTTP Response on the kernel).

I followed the Event Listeners cookbook and I build a Request, but my custom event doesn't have access to the kernel to pass the Request to. Further reading suggests I need a container aware event dispatcher and there is a quick guide here.

Under setup the guide says "Setup is straightforward by injecting a ContainerInterface into the ContainerAwareEventDispatcher".

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher;

$container = new ContainerBuilder();
$dispatcher = new ContainerAwareEventDispatcher($container);

Where does that code go in my app?


Solution

  • You are mixed up, because you are trying to apply instructions, that are for the naked Event Dispatcher component.

    Simply inject container in your event listener service:

    my_listener:
        calls:
            - [setContainer, [@service_container]]