07/10/2014 - DOCTRINE, SYMFONY
The prePersist takes place just before persisting an object into the database and the postPersist takes place right after persist. Example below inserts a new record into UserLog
entity with event subscriber when creating a new record in User entity within controller.
public function createAction()
{
$user = new User();
$user->setUsername('username');
$user->setPassword('password');
$this->entityManager->persist($user);
$this->entityManager->flush();
}
services:
application_backend.event_subscriber.user_entity:
class: Application\BackendBundle\EventSubscriber\UserEntitySubscriber
tags:
- { name: doctrine.event_subscriber }
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();
}
}
}
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)