Reputation: 1398
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.
Upvotes: 0
Views: 2841
Reputation: 349
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);
}
}
Upvotes: 0
Reputation: 36191
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
Upvotes: 2