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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With