Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

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.


UserController.php


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

Listeners.yml


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 }

UserEntityListener.php


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

Result


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)