I need to check if a persisted entity has changed and needs to be updated on the database. What I made (and did not work) was the following:
$product = $enti
Based on my needs, answers here and the docs, I came up with the following solution for a modifiedAt timestamp in an Entity.
/**
* @Doctrine\ORM\Mapping\PreUpdate()
*
* @param \Doctrine\ORM\Event\PreUpdateEventArgs $args
* @return $this
*/
public function preUpdateModifiedAt(\Doctrine\ORM\Event\PreUpdateEventArgs $args)
{
$this->setModifiedAt(new \DateTime('now'));
return $this;
}
This is based on what the docs say about this Event as opposed to the other available ones, such as PostPersist and PreFlush:
PreUpdate is the most restrictive to use event, since it is called right before an update statement is called for an entity inside the EntityManager#flush() method. Note that this event is not triggered when the computed changeset is empty.
Using PreUpdate as opposed to the others lets you leave all the computations and calculation intensive functions to the process already defined by Doctrine. Manually triggering computation of changesets, such as in these answers above are server CPU intensive. The onFlush Event, such as used in the accepted answer is an option (in the way demonstrated), but not if you rely on detecting a change to the Entity, as you can with the function above (preUpdateModifiedAt(PreUpdateEventArgs $args)).