我有自己的自定义User类实现UserInterface。摘录如下:
class User implements UserInterface
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="username", type="string", length=30, unique=true)
*/
protected $username;
...
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
...
在一个控制器中,我希望能够加载当前登录的用户。我这样做:
$user_id = NULL;
$securityContext = $this->container->get('security.context');
if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED'))
$user_obj = $this->get('security.context')->getToken()->getUser();
$user_id = $this->getUser()->getId(); //This yields an exception!
$user_obj->getUsername(); // This works!
}
我可以执行getUsername(),它返回足够的用户名。但是,如果我尝试getId()它不起作用。它产生以下异常:
Attempted to call method "getId" on class "Symfony\Component\Security\Core\User\User
我能从这个对象轻松获取getId()吗?