Symfony:控制器类型提示UserInterface

67up9zun  于 2023-08-06  发布在  其他
关注(0)|答案(2)|浏览(85)

我非常喜欢将当前用户作为参数插入Controller方法中的特性。不过有一件事我不太确定。如果在Controller操作中插入当前用户,如下所示:

public function myAction(UserInterface $currUsr)
{
    $id = $currUsr->getId();
    $email = $currUsr->getEmail();
}

字符串
我不能知道对象$currUsr实际上有方法getId()getEmail(),因为Symfony\Component\Security\Core\User\UserInterface没有这些方法的定义。
那么,字体提示的意义何在......?

f45qwnt8

f45qwnt81#

Symfony 5.2和PHP 8+开始,你可以用你的用户对象的正确类型来提示你的参数,并将#[CurrentUser]属性应用于参数。

public function myAction(#[CurrentUser] ApplicationUser $currUsr)
{
    $id = $currUsr->getId();
    $email = $currUsr->getEmail();
}

字符串

bhmjp9jg

bhmjp9jg2#

如果你需要更具体的类,它有那些UserInterface缺少的方法,你应该使用它。

public function myAction(UserWithMethods $currUsr)
{
    $id = $currUsr->getId();
    $email = $currUsr->getEmail();
}

字符串
不需要添加docblock。

相关问题