How to get userid from eventlistener which are called from AJAX

后端 未结 3 1011
时光取名叫无心
时光取名叫无心 2021-01-12 05:23

I am using symfony2 and FOSUserBundle.

Normally,I can get user data from Controller

$user = $this->get(\'security.context\')->getToken()->g         


        
3条回答
  •  隐瞒了意图╮
    2021-01-12 06:12

    You need to inject the container via Dependency Injection into your listener class in order to acccess it.

    Read more about it in the book chapter.

    your.listener:
        class: Acme\MemberBundle\EventListener\CalendarEventListener
        arguments: ["@service_container"]
    

    Though injecting the whole container is performance-wise not the best idea among with some other reasons like testability ( you should normally only inject the services you need in your class instead of the container )...

    ...in your case if you aren't using a UserCallable you will get a circular reference when injecting @security.context.

    So the quickest solution is injecting the container and adjusting your listener's constructor:

    private $container;
    
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }
    
    
    
    public function someOtherMethod()
    {
        $user = $this->container->get('security.context')->getToken()->getUser();
    
        // ...
    }
    

提交回复
热议问题