在实体刷新上创建实体 [英] Create entity on entity flush

查看:89
本文介绍了在实体刷新上创建实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实现这一点:

例如,我有一个名为 的实体。我需要记录这个实体的字段的更改。

如果用户更改了 实体上的status,我需要创建使用:Symfony2 + doctrine2。

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.

b

推荐答案

您可以使用事件订阅者,并将其附加到ORM事件监听器(在symfony 2中,有关于该文档):

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);
    }
}

您可以最终检查变更集,如我所解释在是否有内置的以获取Doctrine 2实体中所有更改/更新的字段

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.

我离开了执行 IssueLog 的例子,因为这是由你自己的要求。

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

这篇关于在实体刷新上创建实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆