我正在尝试创建自定义事件,但无法使其正常工作。
我做了什么:
1.我在
中创建了识别类的事件namespace Path\ToBundle;
final class CookieEvents
{
const COOKIE_EVENT = 'cookie.event';
}
2.Created事件
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在service.yml
中注册事件监听器kernel.listener.cookie.event:
class: Path\ToBundle\Event\ResponseListener
tags:
- { name: kernel.event_listener, event: cookie.event, method: onCookieInit }
5.接下来我尝试在控制器动作中调度事件
//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
我想要实现的是能够对某些行为发起火灾事件。不幸的是,这不起作用。 事件概念对我来说是新的,我对我在这里所做的事情仍然没有信心,但这是我能够从这些例子中找到的。也许有人可以告诉我,我是否会朝着正确的方向前进并纠正我?如果没有,一些指导甚至更受赞赏。
答案 0 :(得分:4)
谢谢@Qoop指出调度程序的正确用法:
$dispatcher = $this->get('event_dispatcher')
此外,还存在名称空间错误:
class: Path\ToBundle\Event\ResponseListener //incorrect
class: Path\ToBundle\EventListener\ResponseListener //correct