In a Symfony2.8/Doctrine2 application, I need to store in each row of my SQL tables the id of the user who created or updated the row (users can connect with Ldap).
So all my entities inherited of a GenericEntity
which contains this variable (type would be string if I want to store Ldap username):
/** * @var integer * * @ORMColumn(name="zzCreationId", type="string", nullable=false) */ private $creationId;
And I use the prePersistCallback()
to automatically assign this value:
/** * @ORMPrePersist */ public function prePersistCallback() { $currentUser = /* ...... ????? ....... */ ; if ($currentUser->getId() != null) { $this->creationId = $currentUser->getId() ; } else { $this->creationId = 'unknown' ; } return $this; }
But I don’t know how to retrieve the connected user, or how to automatically inject it in the entity… How can I do it?
Advertisement
Answer
You can use a Doctrine entity listener/subscriber instead to inject the security token and get the current logged user:
// src/AppBundle/EventListener/EntityListener.php namespace AppBundleEventListener; use DoctrineORMEventLifecycleEventArgs; use AppBundleEntityGenericEntity; use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorageInterface; class EntityListener { private $tokenStorage; public function __construct(TokenStorageInterface $tokenStorage = null) { $this->tokenStorage = $tokenStorage; } public function prePersist(LifecycleEventArgs $args) { $entity = $args->getEntity(); // only act on "GenericEntity" if (!$entity instanceof GenericEntity) { return; } if (null !== $currentUser = $this->getUser()) { $entity->setCreationId($currentUser->getId()); } else { $entity->setCreationId(0); } } public function getUser() { if (!$this->tokenStorage) { throw new LogicException('The SecurityBundle is not registered in your application.'); } if (null === $token = $this->tokenStorage->getToken()) { return; } if (!is_object($user = $token->getUser())) { // e.g. anonymous authentication return; } return $user; } }
Next register your listener:
# app/config/services.yml services: my.listener: class: AppBundleEventListenerEntityListener arguments: ['@security.token_storage'] tags: - { name: doctrine.event_listener, event: prePersist }