CaptainStiggz
CaptainStiggz

Reputation: 1897

How to inject controller into EventDispatcher in Symfony2

I want to do some post-processing after sending a response object in my Symfony controller. Problem is, the post-processing requires other methods contained in my controller object. I'd like to do something like this:

public function testAction() {
    $dispatcher = new EventDispatcher();
    $dispatcher->addListener('kernel.terminate', function (Event $event) {
        $controller->get('logger');
        $logger->info('hello');
    });
    return new Response();
}

How can I inject the $controller variable into my kernel.terminate post-processing?

Upvotes: 1

Views: 832

Answers (1)

sensi
sensi

Reputation: 569

it seems you need only the container in your service. To get the container injected into your event listener I prefer to create a separate EventListener which you have to register in your container see code:

First create event listener class:

<?php
namespace Acme\DemoBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;

class RequestListener
{
  protected $container;

  public function __construct(ContainerInterface $container)
  {
    $this->container = $container;
  }

  public function onKernelRequest(GetResponseEvent $event)
  {
    $request = $event->getRequest();
    $logger = $this->container->get('logger')->getToken();
    $logger->info('.....');
  }
}

As you can see, we have now the service container injected and we are able to use it.

Next you have to register the service and inject the service container:

services:
  acme.demo.listener.request:
    class: Acme\DemoBundle\Listener\RequestListener
    arguments: [ @service_container ]
    tags:
      - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

Notice in your case you have to select the event you wanna inject to. In my case I used the kernel.request event. You have to select the kernel.terminate event.

That can also be helpful: http://symfony.com/doc/current/cookbook/service_container/event_listener.html

Upvotes: 1

Related Questions