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

报告相同问题?