duanqiaoren9975 2016-01-21 12:02
浏览 5
已采纳

调度员不会发送我的事件symfony

I have an ExampleListener class that look like :

<?php

namespace AppBundle\EventListener;

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

This is my services.yml

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

And then from controller i'm trying to dispatch the event.

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

I don't have any error but the helloWorld function is never called. My event is up :

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

the result is :

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

Why dispatcher doens't call the event right? Thanks.

  • 写回答

2条回答 默认 最新

  • doubaben7394 2016-01-21 12:54
    关注

    You have created a new event dispatcher, which is not the same as Symfony uses to register event listeners you define in you container configuration.

    Instead of creating the event dispatcher yourself, use the one that's already defined by Symfony. You can fetch it from the container, for example in a controller:

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

    If you need to dispatch your event from a service, simply pass the event_dispatcher service as one of constructor arguments:

    services:
        my_service:
            class: Foo\MyService
            arguments:
                - @event_dispatcher
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件