13

How can I achieve this:

For example, I have an entity called Issue. I need to log changes of a field of this entity.
If a user changes the field "status" on the Issue entity I need to create a database record about it with the user, who changed the field, the previous status and the new status.

Using: Symfony2 + doctrine2.

Ocramius
  • 25,171
  • 7
  • 103
  • 107
ideea
  • 353
  • 1
  • 3
  • 10

1 Answers1

21

You can use an event subscriber for that, and attach it to the ORM event listener (in symfony 2, there's docs about that):

namespace YourApp\Subscriber;

use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Events;
use YourApp\Entity\Issue;
use YourApp\Entity\IssueLog;

class IssueUpdateSubscriber implements EventSubscriber
{
    public function onFlush(OnFlushEventArgs $args)
    {
        $em  = $args->getEntityManager();
        $uow = $em->getUnitOfWork();

        foreach ($uow->getScheduledEntityUpdates() as $updated) {
            if ($updated instanceof Issue) {
                $em->persist(new IssueLog($updated));
            }
        }

        $uow->computeChangeSets();
    }

    public function getSubscribedEvents()
    {
        return array(Events::onFlush);
    }
}

You can eventually check the changeset as I've explained at Is there a built-in way to get all of the changed/updated fields in a Doctrine 2 entity.

I left the implementation of IssueLog out of the example, since that is up to your own requirements.

Community
  • 1
  • 1
Ocramius
  • 25,171
  • 7
  • 103
  • 107