在Symfony 2.1中,在preUpdate调用中添加额外的persist调用

11

我的应用程序中有一个preUpdate监听器。当它被触发时,我希望它创建一些额外的记录。下面是基本功能的简化示例。在当前实现中,似乎新事件没有被持久化。这里需要进行其他调用吗?谢谢。

public function preUpdate(Event\LifecycleEventArgs $eventArgs)
{
    $em = $eventArgs->getEntityManager();
    $uow = $em->getUnitOfWork();
    $entity = $eventArgs->getEntity();

    $updateArray = $eventArgs->getEntityChangeSet();

    //Updates
    if (($entity instanceof Bam) === false) {
        $thing = new OtherThing();
        $thing->setFoo('bar');

        $uow->persist($thing);
    }

    $uow->computeChangeSets();
}

$historyRecord是什么? - cheesemacfly
1个回答

26

关键是在刷新后保持它们:

<?php

namespace Comakai\CQZBundle\Handler;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event;

/**
 * 
 */
class YourHandler implements EventSubscriber
{
    protected $things = [];

    public function getSubscribedEvents()
    {
        /**
         * @todo Check if this is running in the console or what...
         */
        if (isset($_SERVER['HTTP_HOST'])) {

            return [
                'preUpdate',
                'postFlush'
            ];
        }

        return [];
    }

    public function preUpdate(Event\LifecycleEventArgs $eventArgs)
    {
        $em = $eventArgs->getEntityManager();
        $uow = $em->getUnitOfWork();
        $entity = $eventArgs->getEntity();

        $updateArray = $eventArgs->getEntityChangeSet();

        //Updates
        if (($entity instanceof Bam) === false) {

            $thing = new OtherThing();
            $thing->setFoo('bar');

            $this->things[] = $thing;
        }
    }

    public function postFlush(Event\PostFlushEventArgs $event)
    {
        if(!empty($this->things)) {

            $em = $event->getEntityManager();

            foreach ($this->things as $thing) {

                $em->persist($thing);
            }

            $this->things = [];
            $em->flush();
        }
    }
}

1
我尝试了这个,但是出现了“PHP致命错误:达到'1000'的最大函数嵌套级别”的错误。 - Igor Mancos
2
检测错误:在"$em->flush();"之前设置"$this->things = [];"非常重要。 - Igor Mancos
抱歉,我也遇到了这个问题!我正在更新我的答案,谢谢Igor。 - coma
一个可能的解决方案,针对@IgorLadela的致命错误:http://stackoverflow.com/questions/16980191/symfony2-maximum-function-nesting-level-of-100-reached-aborting-with-doctrin/31472299#31472299 - webDEVILopers
2
根据当前的Doctrine文档EntityManager#flush()不能在postFlush()内部安全调用。 - Trappar
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接