BentCoder
BentCoder

Reputation: 12740

Checking which event was fired in Event Subscriber

When I insert data into User entity, subscriber below gets fired for pre and post events so I get two records inserted into Dummy entity which is fine up to here. What I need to know is, how can I check which event was fired so that I can use it in setHow() method?

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

Expected result in Dummy table:

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

Subscriber:

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:

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

Upvotes: 0

Views: 666

Answers (1)

qooplmao
qooplmao

Reputation: 17759

You can just pass the name of the event in the method call like..

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

Upvotes: 1

Related Questions