Symfony2 event listener and getting access to Kernel, Request and Response? Symfony2 event listener and getting access to Kernel, Request and Response? symfony symfony

Symfony2 event listener and getting access to Kernel, Request and Response?


There are few mistakes in your services.yml
In order to make your code work, this should look like

services.yml

services:  listener.requestresponse:    class: My\AwesomeBundle\Listener\MyListener    arguments: ['@service_container']    tags:      - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }      - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }

My\AwesomeBundle\Listener\MyListener.php

namespace My\AwesomeBundle\Listener;use Symfony\Component\HttpKernel\Event\GetResponseEvent;use Symfony\Component\HttpKernel\Event\FilterResponseEvent;use Symfony\Component\HttpFoundation\Cookie;use Symfony\Component\DependencyInjection\ContainerInterface;class MyListener{    protected $container;    public function __construct(ContainerInterface $container) // this is @service_container    {        $this->container = $container;    }    public function onKernelRequest(GetResponseEvent $event)    {        $kernel    = $event->getKernel();        $request   = $event->getRequest();        $container = $this->container;    }    public function onKernelResponse(FilterResponseEvent $event)    {        $response  = $event->getResponse();        $request   = $event->getRequest();        $kernel    = $event->getKernel();        $container = $this->container;        switch ($request->query->get('option')) {            case 2:                $response->setContent('Blah');                break;            case 3:                $response->headers->setCookie(new Cookie('test', 1));                break;        }    }}


It seems that you don't actually understand how symfony2 dic works.Your kernel.request listener can handle only cases 1 and 2. For case 3 you should use kernel.response event.

services:   listener.requestresponse:     class: Acme\Bundle\NewBundle\EventListener\RequestListener     tags:       - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }       - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }

The class:

use Symfony\Component\HttpKernel\Event\GetResponseEvent;use Symfony\Component\HttpKernel\Event\FilterResponseEvent;use Symfony\Component\HttpFoundation\Response;class MyListener{   public function onKernelRequest(GetResponseEvent $event)   {       $request = $event->getRequest();       if ($request->query->get('option') == 2) {           $event->setResponse(new Response("hello, message here"));       }   }   public function onKernelResponse(FilterResponseEvent $event)   {       $response = $event->getResponse();       $request  = $event->getRequest();       if ($request->query->get('option') == 3) {           $response->headers->setCookie(new Cookie("test", 1));       }    }}