use Symfony\Component\EventDispatcher\EventDispatcher; // create a new event dispatcher instance $dispatcher = new EventDispatcher(); // add a listener to the dispatcher $dispatcher->addListener('example.event', function ($event) { // handle the event }); // dispatch the example event $dispatcher->dispatch('example.event', new ExampleEvent());
use Symfony\Component\HttpKernel\Kernel; class AppKernel extends Kernel { // ... protected function build(ContainerBuilder $container) { parent::build($container); // get the event dispatcher instance and add a listener $dispatcher = $this->getContainer()->get('event_dispatcher'); $dispatcher->addListener('example.event', function ($event) { // handle the event }); } }In this example, we use the self::getEventDispatcher() method to retrieve the event dispatcher instance from the Symfony Application class. We add a listener to the dispatcher within the build() method of an AppKernel class. This is a common use case for getting the event dispatcher instance in a Symfony-based application.