【问题标题】:dispatcher doesn't dispatch my event symfony调度员没有调度我的事件 symfony
【发布时间】:2016-01-21 12:02:15
【问题描述】:

我有一个 ExampleListener 类,看起来像:

<?php

namespace AppBundle\EventListener;

class ExampleListener
{
    public function helloWorld()
    {
        echo "Hello World!";
    }
}

这是我的 services.yml

services:
    my.event:
        class: AppBundle\EventListener\ExampleListener
        tags:
            - { name: kernel.event_listener, event: my.event, method: helloWorld }

然后我试图从控制器发送事件。

$dispatcher = new EventDispatcher();
$dispatcher->dispatch('my.event')

我没有任何错误,但从未调用 helloWorld 函数。 我的活动开始了:

php bin/console debug:event-dispatcher my.event

结果是:

#1      AppBundle\EventListener\ExampleListener::helloWorld()   0

为什么调度程序没有正确调用事件? 谢谢。

【问题讨论】:

  • 你需要使用已经被容器实例化的事件调度器。试试$this-&gt;container-&gt;get('event_dispatcher')-&gt;dispatch('my.event');
  • 您可以在这里找到示例:stackoverflow.com/a/34162603/3612353

标签: php symfony


【解决方案1】:

你已经创建了一个新的事件调度器,它与 Symfony 用来注册你在容器配置中定义的事件监听器的不同。

不要自己创建事件分发器,而是使用 Symfony 已经定义的分发器。您可以从容器中获取它,例如在控制器中:

$this->container->get('event_dispatcher')->dispatch('my.event');

如果您需要从服务中调度您的事件,只需将 event_dispatcher 服务作为构造函数参数之一传递:

services:
    my_service:
        class: Foo\MyService
        arguments:
            - @event_dispatcher

【讨论】:

    【解决方案2】:

    使用自动连接,现在最好注入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);
        }
    }
    

    【讨论】:

    • 可能迟到了,但值得一提的是,symfony 4.3 的语法是$dispatcher-&gt;dispatch($event, YourEvent::EVENT_TO_DISPATCH);,它可能会抛出一个警告,因为你传递了 2 个参数,而接口定义只包含一个。这是设计使然,为了保持向后兼容性,所以 2 个参数是这样做的方式,第一个是事件对象,第二个是事件名称
    猜你喜欢
    • 1970-01-01
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 2021-01-08
    • 2017-10-21
    相关资源
    最近更新 更多