2014-10-16 267 views
0

被解雇当我将数据插入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 } 
+0

为什么不干脆像'$这个 - >指数的方法调用传递事件的名称(的$ args, 'prePersist')'? – qooplmao 2014-10-16 15:06:35

+0

@Qoop - 我觉得可以喝杯咖啡了!请创建一个答案,以便我可以接受它。感谢您的解决方案。 – BentCoder 2014-10-16 15:13:27

+0

过于复杂的问题。我一直这样做。 – qooplmao 2014-10-16 15:21:09

回答

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); 
     ... 
    } 
} 
+0

不错的一个。谢谢。 – BentCoder 2014-10-16 15:22:26