检查在事件订阅服务器中触发了哪个事件

时间:2014-10-16 14:51:49

标签: symfony doctrine

当我将数据插入User实体时,下面的订阅者会因发布事件而被触发,因此我将两条记录插入Dummy在这里很好的实体。我需要知道的是,我如何检查哪个事件被触发,以便我可以在setHow()方法中使用它?

$dummy->setHow(......);

虚拟表中的预期结果:

id   createdOn             how
1    2014-10-16 12:12:00   prePersist
2    2014-10-16 12:12:01   postPersist

订户:

class UserPost implements EventSubscriber
{
    public function getSubscribedEvents()
    {
        return array('prePersist', 'postPersist');
    }

    public function prePersist(LifecycleEventArgs $args)
    {
        $this->index($args);
    }

    public function postPersist(LifecycleEventArgs $args)
    {
        $this->index($args);
    }

    public function index(LifecycleEventArgs $args)
    {
        $em = $args->getEntityManager();
        $entity = $args->getEntity();

        if ($entity instanceof User) {
            $dummy = new Dummy();
            $dummy->setCreatedOn(new \DateTime('now'));
            $dummy->setHow(.............);
            $em->persist($dummy);
            $em->flush();
        }
    }
}

服务

Service:
    entity.subscriber.user_post:
        class: Site\MainBundle\EventSubscriber\Entity\UserPost
        tags:
            - { name: doctrine.event_subscriber }

1 个答案:

答案 0 :(得分:1)

您只需在方法调用中传递事件的名称,如..

public function prePersist(LifecycleEventArgs $args)
{
    $this->index($args, 'prePersist');
}

public function postPersist(LifecycleEventArgs $args)
{
    $this->index($args, 'postPersist');
}

public function index(LifecycleEventArgs $args, $event)
{
    ...

    if ($entity instanceof User) {
        $dummy = new Dummy();
        $dummy->setCreatedOn(new \DateTime('now'));
        $dummy->setHow($event);
        ...
    }
}