Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually dispatch Doctrine/Kernel events in Symfony?

I need to dispatch a preRemove event manually as I am soft-deleting an entity thus not really removing it. However I would like to trigger the same listener for when the entity is actually removed.

Can I use the EventDispatcher (which doesn't expect a LifecycleEventArgs) like for custom events ? What is the best way to dispatch vanilla events ?

Edit:

Thanks to bosam answer, this is the way to dispatch vanilla events manually:

use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;

$em = $this->getDoctrine()->getManager();
$eventManager = $em->getEventManager();
$eventManager->dispatchEvent(Events::preRemove, new LifecycleEventArgs($user, $em));
like image 641
Remi M Avatar asked Feb 10 '15 11:02

Remi M


2 Answers

You need to call getEventManager() from your entity manager instance.

For example for Doctrine:

$em = $this->getDoctrine()->getManager();
$eventManager = $em->getEventManager();

Then you can dispatch an event by using $eventManager->dispatchEvent($eventName, EventArgs $eventArgs = null).

like image 120
bosam Avatar answered Oct 10 '22 01:10

bosam


So, first Events are not "Thrown", they are Dispatched. What you Throw is Exceptions.

You can use the EventDispatcher to Dispatch custom events and listen to those by specifying listeners in your config.

For more specifics, read up about Dispatching events here: http://symfony.com/doc/current/components/event_dispatcher/introduction.html#creating-and-dispatching-an-event

Also, you can Dispatch any event this way:

$dispatcher = $this->get('event_dispatcher');
$dispatcher->dispatch('string eventName', $eventInstance);

The $eventInstance is in this case created by using a class that extends the Symfony\Component\EventDispatcher\Event class.

You can add any type of object oriented structures to the Event class, like other classes or properties, such as LifeCycleEventArgs and use it with getters and setters (getLifeCycleEventArgs(), setLifeCycleEventArgs()).

I would in your case extend whatever Event class the listener is expecting and add whatever arguments you need and add another listener that fires before or after it based on priority.

like image 29
MichaelHindley Avatar answered Oct 10 '22 01:10

MichaelHindley