0

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,

BleuBizarre
  • 368
  • 2
  • 15

2 Answers2

7

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

Community
  • 1
  • 1
Filo
  • 2,829
  • 1
  • 21
  • 36
  • I already tried it first method : Attempted to call method "getUser" on class ... second method : Notice: Undefined property: XXXXX::$container – BleuBizarre Aug 01 '14 at 20:22
  • Are you calling it in a controller? – Filo Aug 01 '14 at 20:25
  • No, as i mentioned, i'm in an Event in the EventListener folder – BleuBizarre Aug 01 '14 at 20:26
  • thanks, i think that it will work ! i can't say that the answer is usefull because i've no notoriety but thanks :) – BleuBizarre Aug 01 '14 at 20:35
  • I added a notice about the service container injection. – Filo Aug 01 '14 at 20:43
  • Do you know how to put the argument ? it should be as this : but integrating this service_container but it doesn't work ( i must have the wrong integration ^^ ) – BleuBizarre Aug 01 '14 at 20:44
  • If you have any problem with service definition you should give a look at the official documentation: http://symfony.com/doc/current/book/service_container.html#creating-configuring-services-in-the-container – Filo Aug 01 '14 at 20:51
-2
$user_id=$this->getUser()->getId();
dur
  • 15,689
  • 25
  • 79
  • 125