繁体   English   中英

Symfony-事件未派发

[英]Symfony - Event not being dispatched

这是我第一次创建自定义事件分发程序和订户,因此我想尽全力以赴,但我似乎无法找出为什么未分发自定义事件的原因。

我正在遵循文档 ,就我而言,我需要在有人在网站上注册后立即调度事件。

所以在我的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}

在事件探查器的“事件”选项卡中,我确实看到了我的自定义事件被列出,但仍未调度。

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

// ...

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

        $this->get('event_dispatcher')->dispatch(RegistrationEvent::NAME, new RegistrationEvent($user););
    }
}

调度员重复不调度我的活动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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM