Remi M
Remi M

Reputation: 436

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

Upvotes: 5

Views: 3453

Answers (2)

bosam
bosam

Reputation: 168

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

Upvotes: 5

MichaelHindley
MichaelHindley

Reputation: 493

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.

Upvotes: 2

Related Questions