19/10/2014 - DOCTRINE, SYMFONY
In example below, while we're removing a record from User entity, we're inserting records into UserLog entity.
public function updateAction()
{
$user = $this->userRepository->findOneByUsername('inanzzz');
if ($user instanceof User) {
$this->entityManager->remove($user);
$this->entityManager->flush();
}
}
services:
application_backend.event_listener.user_entity:
class: Application\BackendBundle\EventListener\UserEntityListener
tags:
- { name: doctrine.event_listener, event: preRemove }
- { name: doctrine.event_listener, event: postRemove }
namespace Application\BackendBundle\EventListener;
use Application\BackendBundle\Entity\User;
use Application\BackendBundle\Entity\UserLog;
use Doctrine\ORM\Event\LifecycleEventArgs;
class UserEntityListener
{
public function preRemove(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof User) {
$userLog = new UserLog();
$userLog->setUserId($entity->getId());
$userLog->setMessage('preRemove at ' . date('d/m/Y H:i:s'));
$em = $args->getEntityManager();
$em->persist($userLog);
$em->flush();
}
}
public function postRemove(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof User) {
$userLog = new UserLog();
$userLog->setUserId($entity->getId());
$userLog->setMessage('postRemove at ' . date('d/m/Y H:i:s'));
$em = $args->getEntityManager();
$em->persist($userLog);
$em->flush();
}
}
}
mysql> SELECT id, username, password, pre_update FROM user LIMIT 1;
+----+----------+------------------------------------------+------------+
| id | username | password | pre_update |
+----+----------+------------------------------------------+------------+
| 32 | inanzzz | 09cd68a2a77b22a312dded612dd0d9988685189f | NULL |
+----+----------+------------------------------------------+------------+
1 row in set (0.00 sec)
mysql> SELECT * FROM user_log;
Empty set (0.00 sec)
mysql> SELECT * FROM user WHERE username = 'inanzzz';
Empty set (0.00 sec)
mysql> SELECT * FROM user_log;
+----+---------+-----------------------------------+
| id | user_id | message |
+----+---------+-----------------------------------+
| 10 | 32 | preRemove at 29/06/2015 22:07:55 |
| 11 | NULL | postRemove at 29/06/2015 22:07:55 |
+----+---------+-----------------------------------+
3 rows in set (0.00 sec)