Symfony2 Special Event Manager and Listener

I am trying to create a custom event but cannot make it work.

What I've done:

1.I created an event identification class in

namespace Path\ToBundle; final class CookieEvents { const COOKIE_EVENT = 'cookie.event'; } 

2.Created event

 namespace Path\ToBundle\EventListener; use Path\ToBundle\Event\FilterResponseEvent; class ResponseListener { public function onCookieInit(FilterResponseEvent $event) { //some complex logic goes here echo('test'); } } 

3 generated event listener

 namespace Path\ToBundle\Event; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\HttpFoundation\Response; class FilterResponseEvent extends Event { protected $response; public function __construct(Response $response) { $this->response = $response; } public function getResponse() { return $this->response; } } 

4. I tried to register an event listener inside service.yml

 kernel.listener.cookie.event: class: Path\ToBundle\Event\ResponseListener tags: - { name: kernel.event_listener, event: cookie.event, method: onCookieInit } 

5.Next I'm trying to send an event inside a controller action

 //includes before class use Symfony\Component\EventDispatcher\EventDispatcher; use Path\ToBundle\Event\FilterResponseEvent; //inside controller action //... $response variable is created $dispatcher = new EventDispatcher(); $event = new FilterResponseEvent($response); $dispatcher->dispatch(CookieEvents::COOKIE_EVENT, $event); return $response; //EOF controller action 

What I'm trying to achieve is the possibility of a fire on certain actions. Unfortunately this does not work. The concept of events is new to me, and I'm still not sure what I'm doing here, but this is what I was able to understand from the examples. Maybe someone will tell me if I will go in the right direction and correct it? If not, some recommendations are even more appreciated.

+8
events symfony
source share
1 answer

Thanks @Qoop for pointing out the correct use of the dispatcher:

 $dispatcher = $this->get('event_dispatcher') 

In addition, there was a namespace error:

 class: Path\ToBundle\Event\ResponseListener //incorrect class: Path\ToBundle\EventListener\ResponseListener //correct 
+4
source share

All Articles