我想创建名为user_logged
的自定义事件,这样我就可以将侦听器连接到这些事件。
每当用户登录时,我想执行一些功能。
创建一个扩展SymfonyComponentEventDispatcherEvent
的类。
然后,使用事件调度器服务来调度事件:
$eventDispatcher = $container->get('event_dispatcher');
$eventDispatcher->dispatch('custom.event.identifier', $event);
您可以注册您的事件侦听器服务,如下所示:
tags:
- { name: kernel.event_listener, event: custom.event.identifier, method: onCustomEvent }
这个答案是一个小的扩展答案。
services.yml
custom.event.home_page_event:
class: AppBundleEventSubscriberHomePageEventSubscriber
tags:
- { name: kernel.event_listener, event: custom.event.home_page_event, method: onCustomEvent }
AppBundle/EventSubscriber/HomePageEventSubscriber.php
namespace AppBundleEventSubscriber;
class HomePageEventSubscriber
{
public function onCustomEvent($event)
{
var_dump($event->getCode());
}
}
AppBundle/Event/HomePageEvent.php
namespace AppBundleEvent;
use SymfonyComponentEventDispatcherEvent;
class HomePageEvent extends Event
{
private $code;
public function setCode($code)
{
$this->code = $code;
}
public function getCode()
{
return $this->code;
}
}
任意位置,例如主页控制器
use AppBundleEventHomePageEvent;
// ...
$eventDispatcher = $this->get('event_dispatcher');
$event = new HomePageEvent();
$event->setCode(200);
$eventDispatcher->dispatch('custom.event.home_page_event', $event);