保存新实体后的Symfony事件监听器

时间:2017-04-06 10:00:21

标签: symfony

我需要检查实体是否是特定实体的实例,并在保存新实体后执行某些操作。像cakephp中的方法afterSave之类的东西。我尝试了postFlushonFlushpostPersistpostLoad

的appbundle /事件监听/ DoSomethingAfterSaveNewEntity.php

namespace AppBundle\EventListener;

use Doctrine\ORM\Event\OnFlushEventArgs;
use AppBundle\Entity\SomeEntity;

class DoSomethingAfterSaveNewEntity 
{
    public function onFlush(OnFlushEventArgs $args)
    {   
        $entity = $args->getEntity();
        $em = $args->getEntityManager();
        $uow = $em->getUnitOfWork();

        if (!$entity instanceof SomeEntity) {
          die('not instance!!!');
        }

        die('post flush!!!');
        $entityManager = $args->getEntityManager();
    }
}

1 个答案:

答案 0 :(得分:5)

您的想法是正确的,但您应该为此创建一个新的EntityListener或EntitySubscriber。因此,实体本身并不倾听其变化(不良做法)。

services.yml

your.entity.subscriber:
      class: AppBundle\Subscriber\YourEntitySubscriber
      tags:
          - { name: doctrine.event_subscriber, connection: default }

YourEntitySubscriber.php

<?php

namespace AppBundle\Subscriber;

use AppBundle\Entity\YourEntity;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;

class YourEntitySubscriber implements EventSubscriber
{
    /**
     * @return array
     */
    public function getSubscribedEvents()
    {
        return array(
            'postPersist',
            'postUpdate',
        );
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function postPersist(LifecycleEventArgs $args)
    {
        // Do whatever you want (after entity creation)
    }

    /**
     * @param LifecycleEventArgs $args
     */
    public function postUpdate(LifecycleEventArgs $args)
    {
        // Do whatever you want
    }
}

此外,您可以在此处获得更多示例:event_listeners_subscribers