0

I am curious to know if we can write lifecycle callbacks in an entity repository class rather than in the entity itself?

I am aware that I can write the callback in an abstract class for that my abstract base class has to be annotated as Mapped Superclasses and include the HasLifecycleCallbacks-Annotation

1
  • No but you can register your repository as a doctrine event listener and possibly achieve your goals. Commented Feb 19, 2015 at 14:28

2 Answers 2

0

The Answer is no, but if you like to write you lifecycle callbacks in separate class you can do it using Entity Listeners like this in Doctrine2.4:

Register your listener:

<doctrine-mapping> <entity name="MyProject\Entity\User"> <entity-listeners> <entity-listener class="UserListener"/> </entity-listeners> <!-- .... --> </entity> </doctrine-mapping> 

and write your class like this:

class UserListener { public function preUpdate(User $user, PreUpdateEventArgs $event) { // Do something on pre update. } } 

Other Methods are also available which can be use like this:

<doctrine-mapping> <entity name="MyProject\Entity\User"> <entity-listeners> <entity-listener class="UserListener"> <lifecycle-callback type="preFlush" method="preFlushHandler"/> <lifecycle-callback type="postLoad" method="postLoadHandler"/> <lifecycle-callback type="postPersist" method="postPersistHandler"/> <lifecycle-callback type="prePersist" method="prePersistHandler"/> <lifecycle-callback type="postUpdate" method="postUpdateHandler"/> <lifecycle-callback type="preUpdate" method="preUpdateHandler"/> <lifecycle-callback type="postRemove" method="postRemoveHandler"/> <lifecycle-callback type="preRemove" method="preRemoveHandler"/> </entity-listener> </entity-listeners> <!-- .... --> </entity> </doctrine-mapping> 

More Details are here

Another Way to do it is Write Even Listeners Like this:

use Doctrine\ORM\Events; use Doctrine\Common\EventSubscriber; use Doctrine\Common\Persistence\Event\LifecycleEventArgs; class MyEventSubscriber implements EventSubscriber { public function getSubscribedEvents() { return array( Events::postUpdate, ); } public function postUpdate(LifecycleEventArgs $args) { $entity = $args->getObject(); $entityManager = $args->getObjectManager(); // perhaps you only want to act on some "Product" entity if ($entity instanceof Product) { // do something with the Product } } 

The only disadvantage is:

Lifecycle events are triggered for all entities. It is the responsibility of the listeners and subscribers to check if the entity is of a type it wants to handle.

Sign up to request clarification or add additional context in comments.

Comments

0

Probably you need yo create a custom repository. Take a look at this post: How exactly do I create a custom EntityManager in Symfony2/Doctrine?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.