Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 custom event dispatcher and listener

Tags:

events

symfony

I am trying to create custom event, but can't make it work.

What I have done:

1.I created event identifying 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.created 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.Tried to register 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 try to dispatch event inside 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 to be able fire event on certain actions. Unfortunately this doesn't work. The events concept is new to me and, I am still not confident in what I am doing here, but's it what I was able to figure out of the examples. Maybe someone could tell me if I'm going to right direction and correct me? If not, some guidance is even more appreciated.

like image 384
antanas_sepikas Avatar asked Jul 16 '14 08:07

antanas_sepikas


1 Answers

Thanks, @Qoop for pointing out correct usage of dispatcher:

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

Also, there was namespace error:

class: Path\ToBundle\Event\ResponseListener  //incorrect

class: Path\ToBundle\EventListener\ResponseListener  //correct
like image 143
antanas_sepikas Avatar answered Sep 28 '22 07:09

antanas_sepikas