Home >Backend Development >PHP Tutorial >How to Track Entity Changes in Doctrine 2?

How to Track Entity Changes in Doctrine 2?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 09:19:02369browse

How to Track Entity Changes in Doctrine 2?

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:

  1. Obtain the UnitOfWork:

    $uow = $em->getUnitOfWork();
  2. Compute Changes:

    $uow->computeChangeSets();
  3. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn