简体   繁体   中英

Access current user in entity lifecycle callback

In my doctrine entity I have a lifecycle callback that needs access to the currently logged in user (something like TokenStorage ).

Can I stick to the lifecycle callback or do I have to switch to an event listener where the token storage is injected?

/** @ORM\HasLifecycleCallbacks() */
class Report {
    /** @ORM\PrePersist */
    public function onPrePersist(LifecycleEventArgs $args)
    {
        $this->updatedAt = new \DateTime();
        $this->lastUpdatedBy = ???->getToken()->getUser(); // <-----
    }
}

the good way to do this is to use the doctrine event listener:

file service.yml

    services:
         my_report_listener :
          class : App\EventListener\ReportListner
          arguments: ['@security.token_storage']
          tags:
             - { name: doctrine.event_listener, event: prePersist }

your event listener class :

    class ReportListner {

      private $tokenStorage;

      public function __construct(TokenStorageInterface $tokenStorage)
      {
         $this->tokenStorage= $tokenStorage;
      }

      public function prePersist(LifecycleEventArgs $args)
      {
        $entity = $args->getObject();
        if($entity instanceof Report){
         $current_user = $this->tokenStorage->getToken()->getUser();
        }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM