Karolis
Karolis

Reputation: 2618

Symfony / Doctrine EventSubscriber vs EntityListener

Edit: To avoid confusion, this question is about Entity Listener and not about Event Listener

I am learning Symfony events and looking into how EntityListeners and EventSubscribers work.

As I understand, EntityListener is attached to only one entity, while EventSubscriber methods get called for all entities. Eventually in the EventSubscriber class I have to do something like this:

public function prePersist(LifecycleEventArgs $args)
{
    $object = $args->getObject();

    if ($object instanceof xxxxxxx) {
        $this->doSomething();
    }
}

So it would appear that whenever I need to listen to events of a single entity, I should use EntityListener, and when I want to listen to events of all Doctrine entities, I should use an EventSubscriber.

But... looking at the most popular bundles, like FOSUserBundle, VichUploaderBundle, SonataMediaBundle, etc, they all use EventSubscriber interface and none of them use EntityListener. Even though they need to listen to only one entity.

I haven't yet seen a bundle which would make use of EntityListener.

My question is: why?

From my point of view, EntityListener should be more efficient as it only fires for a single entity. Calling say 20 pre-update subscribers for each and every entity update doesn't seem very optimized?

Upvotes: 0

Views: 1039

Answers (1)

Paweł Mikołajczuk
Paweł Mikołajczuk

Reputation: 3812

EntityListener is attached to only one entity, while EventSubscriber methods get called for all entities.

You can't compare EntityListeners to EventListeners/EventSubscribers.

Different from Implementing Event Listeners an Entity Listener is invoked just to the specified entity.

Entity Listener: An entity listener is a lifecycle listener class used for an entity.

Even Listeners: They sit at a level above the entities and allow you to implement re-usable behaviors across different entity classes.

Citing @stof about differences between Event Listeners and Event Subscribers:

The main advantage of subscribers (and the reason why Symfony switched to them in 2.1) is that it keeps the knowledge of the events in the class rather than in the service definition, making it easier to reuse the listener in other contexts (Silex for instance, which is why Symfony code was changed).

On the other hand, register listeners through the service definition gives more flexibility to the DI setup of the bundle (allowing to add the tag conditionally based on the config for instance)

Upvotes: 0

Related Questions