如何创建Symfony2的自定义事件(How to create custom event in s

2019-06-26 13:28发布

我想创建一个名为自定义事件user_logged ,这样我可以附上我的听众对这些事件。

我想执行每当用户已经登录一些功能。

Answer 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 }


Answer 2:

这个答案是有点扩展答案 。

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);


文章来源: How to create custom event in symfony2