PrePersist veritabanına bilgi girmeden tam önce çalışır, postPersist ise bilgi girişinin tam ardından çalışır. Aşağıdaki örnek test amaçlı olarak User ve UserLog entity üzerlerine kuruludur. User tablosuna controller içindeyken yeni bir kayıt girerken, aynı anda event subscriber ile UseLog entitisine kayıt girer.


UserController.php


public function createAction()
{
$user = new User();
$user->setUsername('username');
$user->setPassword('password');
$this->entityManager->persist($user);
$this->entityManager->flush();
}

Subscriber.yml


services:
application_backend.event_subscriber.user_entity:
class: Application\BackendBundle\EventSubscriber\UserEntitySubscriber
tags:
- { name: doctrine.event_subscriber }

UserEntitySubscriber.php


namespace Application\BackendBundle\EventSubscriber;

use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Application\BackendBundle\Entity\User;
use Application\BackendBundle\Entity\UserLog;

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

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

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

public function index(LifecycleEventArgs $args, $event)
{
$entity = $args->getEntity();

if ($entity instanceof User) {
$log = new UserLog();
$log->setUserId($entity->getId());
$log->setMessage($event . ' at ' . date('d/m/Y H:i:s'));

$em = $args->getEntityManager();
$em->persist($log);
$em->flush();
}
}
}

Sonuç


mysql> SELECT * FROM user;
+----+----------+------------+
| id | username | password |
+----+----------+------------+
| 1 | MEBKZT | 1436015275 |
+----+----------+------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM user_log;
+----+---------+------------------------------------+
| id | user_id | message |
+----+---------+------------------------------------+
| 1 | NULL | prePersist at 29/06/2015 20:06:56 |
| 2 | 1 | postPersist at 29/06/2015 20:06:56 |
+----+---------+------------------------------------+
2 rows in set (0.00 sec)