Tracking Entity Changes in Doctrine 2
Doctrine 2 provides a way to track the changed fields of an entity using the EntityManager and UnitOfWork.
Suppose you have an entity $e and modify its fields:
$e->setFoo('a'); $e->setBar('b');
To retrieve an array of changed fields:
Obtain the UnitOfWork:
$uow = $em->getUnitOfWork();
Compute Changes:
$uow->computeChangeSets();
Get Entity Changes:
$changeset = $uow->getEntityChangeSet($e);
The $changeset will contain all modified attribute-value pairs:
[ 'foo' => ['old' => 'oldFoo', 'new' => 'a'], 'bar' => ['old' => 'oldBar', 'new' => 'b'], ]
Note for PreUpdate Listeners:
If attempting to retrieve updated fields within a preUpdate listener, skip the change set computation as it has already occurred. Simply call getEntityChangeSet to retrieve the changes.
Warning:
Using this method outside of Doctrine event listeners can disrupt its operation.
The above is the detailed content of How to Track Entity Changes in Doctrine 2?. For more information, please follow other related articles on the PHP Chinese website!