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

时间:2012-07-26 01:22:40

标签: php symfony events observer-pattern symfony-components

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

我想在用户登录时执行少量功能。

2 个答案:

答案 0 :(得分:76)

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

答案 1 :(得分:28)

这个答案有点延伸answer

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