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

我想创建自定义调用的事件,以便我可以将侦听器附加到这些事件。user_logged

我想在用户登录时执行一些功能。


答案 1

创建一个扩展 的类。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 }

答案 2

这个答案是有点延伸的答案

服务.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/Event/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);

推荐