是否有可能在实体存储库类而不是实体中编写生命周期回调?

时间:2015-02-19 14:11:54

标签: symfony callback lifecycle

我很想知道我们是否可以在实体存储库类中而不是在实体本身中编写生命周期回调?

我知道我可以在抽象类中编写回调,因为我的抽象基类必须注释为Mapped Superclasses并包含HasLifecycleCallbacks-Annotation

2 个答案:

答案 0 :(得分:0)

答案是否定的,但如果您想在单独的类中编写生命周期回调,可以使用Doctrine2.4中的实体监听器来执行此操作:

注册您的听众:

<doctrine-mapping>
    <entity name="MyProject\Entity\User">
        <entity-listeners>
            <entity-listener class="UserListener"/>
        </entity-listeners>
        <!-- .... -->
    </entity>
</doctrine-mapping>

并写下你的课程:

class UserListener
{
    public function preUpdate(User $user, PreUpdateEventArgs $event)
    {
        // Do something on pre update.
    }
}

其他方法也可以使用,如下所示:

<doctrine-mapping>
    <entity name="MyProject\Entity\User">
         <entity-listeners>
            <entity-listener class="UserListener">
                <lifecycle-callback type="preFlush"      method="preFlushHandler"/>
                <lifecycle-callback type="postLoad"      method="postLoadHandler"/>

                <lifecycle-callback type="postPersist"   method="postPersistHandler"/>
                <lifecycle-callback type="prePersist"    method="prePersistHandler"/>

                <lifecycle-callback type="postUpdate"    method="postUpdateHandler"/>
                <lifecycle-callback type="preUpdate"     method="preUpdateHandler"/>

                <lifecycle-callback type="postRemove"    method="postRemoveHandler"/>
                <lifecycle-callback type="preRemove"     method="preRemoveHandler"/>
            </entity-listener>
        </entity-listeners>
        <!-- .... -->
    </entity>
</doctrine-mapping>

更多详情为here

另一种方法是写Even Even Listeners,如下所示:

use Doctrine\ORM\Events;
use Doctrine\Common\EventSubscriber;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;

class MyEventSubscriber implements EventSubscriber
{
    public function getSubscribedEvents()
    {
        return array(
            Events::postUpdate,
        );
    }

    public function postUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();
        $entityManager = $args->getObjectManager();

        // perhaps you only want to act on some "Product" entity
        if ($entity instanceof Product) {
            // do something with the Product
        }
    }

唯一的缺点是:

  

为所有实体触发生命周期事件。它是   听众和订户的责任是检查实体   是一种它想要处理的类型。

答案 1 :(得分:0)

您可能需要创建自定义存储库。看一下这篇文章:How exactly do I create a custom EntityManager in Symfony2/Doctrine?