[FIXED] Doctrine 2 – Disable PrePersist from outside of entity

Issue

I’m trying to disable an entity event from outside of an entity in Doctrine 2. Everytime we insert a new record into our table, few file operations need to be run, which have been implemented in a method with the prePersist annotation. However I also need to run some data fixtures and skip the file operation part as part of the testing.

Basically I’m asking if it’s possible to disable all prePersist events through the entity manager without changing anything in the entity.

Solution

Disabling lifecycle callbacks is not possible with the ORM API.

The problem comes from the fact that external listeners are called after the entity’s lifecycle callbacks are invoked, so even a transient property that disables the callback (set by an external listener/subscriber) won’t work.

Consider moving the logic from the entity to an external listener/subscriber instead: that way, you will gain a lot more flexibility and you would be able to turn off the behavior you described by reusing a status internal to the listener/subscriber itself.

// ...

public function prePersist(LifecycleEventArgs $args)
{
    if ($this->skipCondition($args->getEntity()) {
        return;
    }

    $this->manipulate($args->getEntity());
}

// ...

Answered By – Ocramius

Answer Checked By – Cary Denson (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published