0

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.

Isky
  • 1,328
  • 2
  • 14
  • 33
  • 2
    You need to use the event dispatcher that has been instantiated by the container. Try `$this->container->get('event_dispatcher')->dispatch('my.event');` – qooplmao Jan 21 '16 at 12:10
  • You can find example here: http://stackoverflow.com/a/34162603/3612353 – cn007b Jan 21 '16 at 12:13

2 Answers2

2

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
Jakub Zalas
  • 35,761
  • 9
  • 93
  • 125
0

With auto-wiring, it is now better to inject the 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);
    }
}
Laurent
  • 289
  • 1
  • 3
  • 17
  • 2
    Maybe late to the party, but it's worth mentioning, that symfony 4.3 syntax is `$dispatcher->dispatch($event, YourEvent::EVENT_TO_DISPATCH);` which may throw a warning because you pass 2 arguments, and the interface definition contains just one. It's by design, to maintain backwards compatibility, so 2 arguments is the way to do it, where the first is the event object, and the second is the event name – man Sep 26 '19 at 23:12