Reputation: 378
i'm trying to get the user id in an event listener in Symfony 2.4 but as far as I know EventListener isn't called by a controller so i can't user the
$this->getUser();
What is the best way to get the id?
I thought about giving it in services.yml that calls the event.
Thanks for anyhelp or any documentation that would help.
Regards,
Upvotes: 0
Views: 3643
Reputation: 2839
In a controller you should be able since symfony 2.1 to simple use
$user = $this->getUser();
$userId = $user->getId();
Or you can get the current logged in user object from security context
$user = $this->container->get('security.context')->getToken()->getUser();
$userId = $user->getId();
Or using the FOSUserBundle service (apparently it is an alternative of the built-in method getUser(), as the comment in the linked page said )
$userManager = $this->container->get('fos_user.user_manager');
$user = $userManager->findUserByUsername($this->container->get('security.context')->getToken()->getUser());
$userId = $user->getId();
Update
If you are in a event listener you need to inject the container via Dependency Injection into your listener class in order to acccess it. Give a look at this answer: https://stackoverflow.com/a/17022330/3625883
Second update
The previous links do exactly what you asked but I want only to notice a thing: in general is not a good practise to inject the entire service container, you should inject only the security.context . For more information : https://stackoverflow.com/a/15922525/3625883
Upvotes: 7