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

2022-01-16 00:00:00 php symfony doctrine symfony-2.1 listener

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

I have a preUpdate listener in my app. When it is fired I want it to create some additional records. A simplified example of the basic functionality is below. In this current implementation it would appear that the new events are not being persisted. Are there other calls I need to be making here? Thanks.

public function preUpdate(EventLifecycleEventArgs $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();
}

推荐答案

关键是在flush之后持久化它们:

The key is to persist them after the flush:

<?php

namespace ComakaiCQZBundleHandler;

use SymfonyComponentDependencyInjectionContainerInterface;
use DoctrineCommonEventSubscriber;
use DoctrineORMEvent;

/**
 * 
 */
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(EventLifecycleEventArgs $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(EventPostFlushEventArgs $event)
    {
        if(!empty($this->things)) {

            $em = $event->getEntityManager();

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

                $em->persist($thing);
            }

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

相关文章