在实体刷新时创建实体 [英] Create entity on entity flush
问题描述
我怎样才能做到这一点:
How can I achieve this:
例如,我有一个名为 Issue 的实体.我需要记录此实体字段的更改.
如果用户更改了 Issue 实体上的字段 "status",我需要与用户一起创建一个关于它的数据库记录,谁更改了该字段、以前的状态和新状态.
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.
使用:Symfony2 + Doctic2.
Using: Symfony2 + doctrine2.
推荐答案
您可以使用 事件订阅者,并将其附加到 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 YourAppSubscriber;
use DoctrineCommonEventSubscriber;
use DoctrineORMEventOnFlushEventArgs;
use DoctrineORMEvents;
use YourAppEntityIssue;
use YourAppEntityIssueLog;
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屋!