1

这是我第一次使用创建自定义事件调度程序和订阅者,所以我试图绕开它,我似乎无法找出为什么我的自定义事件没有被调度。

我正在关注文档,就我而言,一旦有人在网站上注册,我就需要发送一个事件。

所以在我的内部我registerAction()试图发送这样的事件

$dispatcher = new EventDispatcher();
$event = new RegistrationEvent($user);
$dispatcher->dispatch(RegistrationEvent::NAME, $event);

这是我的RegistrationEvent

namespace AppBundle\Event;
use AppBundle\Entity\User;
use Symfony\Component\EventDispatcher\Event;

class RegistrationEvent extends Event
{
    const NAME = 'registration.complete';

    protected $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function getUser(){
        return $this->user;
    }

}

这是我的RegistrationSubscriber

namespace AppBundle\Event;    
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RegistrationSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::RESPONSE => array(
                array('onKernelResponsePre', 10),
                array('onKernelResponsePost', -10),
            ),
            RegistrationEvent::NAME => 'onRegistration'
        );

    }
    public function onKernelResponsePre(FilterResponseEvent $event)
    {
        // ...
    }

    public function onKernelResponsePost(FilterResponseEvent $event)
    {
        // ...
    }
    public function onRegistration(RegistrationEvent $event){

        var_dump($event);
        die;

    }

}

完成此操作后,我希望注册过程将在该函数处停止,onRegistration但这并没有发生,然后我查看了分析器的事件选项卡,我也没有看到我的事件列出了它们。

我在这里想念什么?朝着正确的方向推动将不胜感激。

更新: 我想我需要为自定义事件注册一个服务,所以我在里面添加了以下代码services.yml

app.successfull_registration_subscriber:
    class: AppBundle\Event\RegistrationSubscriber
    arguments: ["@doctrine.orm.entity_manager"]
    tags:
        - { name: kernel.event_subscriber}

在探查器的事件选项卡中,我确实看到我的自定义事件被列出,但它仍然没有调度。

4

2 回答 2

5

通过创建您自己的EventDispatcher实例,您调度了一个其他侦听器永远无法侦听的事件(它们未附加到此调度程序实例)。您需要使用该event_dispatcher服务来通知您使用kernel.event_listenerandkernel.event_subscriber标签标记的所有侦听器:

// ...

class RegistrationController extends Controller
{
    public function registerAction()
    {
        // ...

        $this->get('event_dispatcher')->dispatch(RegistrationEvent::NAME, new RegistrationEvent($user););
    }
}
于 2016-04-28T16:36:38.383 回答
1

调度程序的重复不会调度我的事件 symfony

使用自动布线,现在最好注入EventDispatcherInterface

<?php
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
//...

class DefaultController extends Controller
{
    public function display(Request $request, EventDispatcherInterface $dispatcher)
    {
        //Define your event
        $event = new YourEvent($request);
        $dispatcher->dispatch(YourEvent::EVENT_TO_DISPATCH, $event);
    }
}
于 2018-08-01T11:46:53.013 回答