如何在symfony2中创build自定义事件

我想要创build一个名为user_logged自定义事件,以便我可以将侦听器附加到这些事件。

每当用户login时,我都想执行一些function。

创build一个扩展Symfony\Component\EventDispatcher\Event

然后,使用事件分派器服务来分派事件:

 $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: AppBundle\EventSubscriber\HomePageEventSubscriber tags: - { name: kernel.event_listener, event: custom.event.home_page_event, method: onCustomEvent } 

的appbundle / EventSubscriber / HomePageEventSubscriber.php

 namespace AppBundle\EventSubscriber; class HomePageEventSubscriber { public function onCustomEvent($event) { var_dump($event->getCode()); } } 

的appbundle /事件/ HomePageEvent.php

 namespace AppBundle\Event; use Symfony\Component\EventDispatcher\Event; class HomePageEvent extends Event { private $code; public function setCode($code) { $this->code = $code; } public function getCode() { return $this->code; } } 

你希望的任何地方,例如在主页控制器

  use AppBundle\Event\HomePageEvent; // ... $eventDispatcher = $this->get('event_dispatcher'); $event = new HomePageEvent(); $event->setCode(200); $eventDispatcher->dispatch('custom.event.home_page_event', $event);