Symfony getting logged in user's id

ぐ巨炮叔叔 提交于 2019-11-26 20:18:45

问题


I am developing an application using Symfony2 and doctrine 2. I would like to know how can I get the currently logged in user's Id.


回答1:


Current Symfony versions (Symfony 4, Symfony >=3.2)

Since Symfony >=3.2 you can simply expect a UserInterface implementation to be injected to your controller action directly. You can then call getId() to retrieve user's identifier:

class DefaultController extends Controller
{
    // when the user is mandatory (e.g. behind a firewall)
    public function fooAction(UserInterface $user)
    {
        $userId = $user->getId(); 
    }

    // when the user is optional (e.g. can be anonymous)
    public function barAction(UserInterface $user = null) 
    {
        $userId = null !== $user ? $user->getId() : null;
    }
}

You can still use the security token storage as in all Symfony versions since 2.6. For example, in your controller:

$user = $this->get('security.token_storage')->getToken()->getUser();

Note that the Controller::getUser() shortcut mentioned in the next part of this answer is no longer encouraged.

Legacy Symfony versions

The easiest way to access the user used to be to extend the base controller, and use the shortcut getUser() method:

$user = $this->getUser();

Since Symfony 2.6 you can retrieve a user from the security token storage:

$user = $this->get('security.token_storage')->getToken()->getUser();

Before Symfony 2.6, the token was accessible from the security context service instead:

$user = $this->get('security.context')->getToken()->getUser();

Note that the security context service is deprecated in Symfony 2 and was removed in Symfony 3.0.




回答2:


In symfony2, we can get this simpler by this code:

$id = $this->getUser()->getId();



回答3:


You can get the variable with the code below:

$userId = $this->get('security.context')->getToken()->getUser()->getId();



回答4:


This can get dressed in the method:

/**
 * Get user id
 * @return integer $userId
 */
protected function getUserId()
{
    $user = $this->get('security.context')->getToken()->getUser();
    $userId = $user->getId();

    return $userId;
}

And induction $this->getUserId()

public function example()
{
    print_r($this->getUserId()); 
}


来源:https://stackoverflow.com/questions/10537879/symfony-getting-logged-in-users-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!