在Symfony 2.1中添加额外的持久调用以调用preUpdate

key*_*red 11 php doctrine listener symfony symfony-2.1

我的应用程序中有一个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();
}
Run Code Online (Sandbox Code Playgroud)

com*_*oma 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 检测错误:设置"$ this-> things = [];"非常重要 在"$ em-> flush();"之前 (2认同)
  • 根据目前[Doctrine文档](http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#postflush):`EntityManager#flush()`不能在`postFlush()`中安全地调用. (2认同)