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 inserts a new record into UserLog entity with event subscriber 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();
}

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

Result


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)