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 updates actual User
entity and UserLog
entity with event listener 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_listener.user_entity:
class: Application\BackendBundle\EventListener\UserEntityListener
tags:
- { name: doctrine.event_listener, event: prePersist }
- { name: doctrine.event_listener, event: postPersist }
namespace Application\BackendBundle\EventListener;
use Application\BackendBundle\Entity\User;
use Application\BackendBundle\Entity\UserLog;
use Doctrine\ORM\Event\LifecycleEventArgs;
class UserEntityListener
{
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
/**
* Same entity
*/
if ($entity instanceof User) {
$entity->setPrePersist(date('d/m/Y H:i:s'));
}
/**
* Log entity
*/
if ($entity instanceof User) {
$log = new UserLog();
$log->setUserId($entity->getId());
$log->setMessage('prePersist at ' . date('d/m/Y H:i:s'));
$em = $args->getEntityManager();
$em->persist($log);
$em->flush();
}
}
public function postPersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
/**
* Same entity
*/
if ($entity instanceof User) {
$entity->setPostPersist(date('d/m/Y H:i:s'));
}
/**
* Log entity
*/
if ($entity instanceof User) {
$log = new UserLog();
$log->setUserId($entity->getId());
$log->setMessage('postPersist at ' . date('d/m/Y H:i:s'));
$em = $args->getEntityManager();
$em->persist($log);
$em->flush();
}
}
}
mysql> SELECT id, username, password, pre_persist, post_persist FROM user;
+----+----------+------------+---------------------+---------------------+
| id | username | password | pre_persist | post_persist |
+----+----------+------------+---------------------+---------------------+
| 1 | IVAHDL | 1435604816 | 29/06/2015 20:06:56 | 29/06/2015 20:06:56 |
+----+----------+------------+---------------------+---------------------+
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)