【问题标题】:Symfony: Controller type hinting UserInterfaceSymfony:控制器类型提示 UserInterface
【发布时间】:2018-07-27 19:13:33
【问题描述】:

我真的很喜欢在 Controller 方法中插入当前用户作为参数的功能。但是,我不确定一件事。如果我将当前用户插入到这样的控制器操作中:

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

我不知道$currUsr 对象实际上有getId()getEmail() 方法,因为Symfony\Component\Security\Core\User\UserInterface 没有定义这些方法。

那么类型提示的意义何在..?

【问题讨论】:

  • 类型提示的要点是 SF 注入用户而无需您检索它。 Stof 在此处的评论 #6 中提到了您不能使用核心 UserInterface 的子类的原因:symfony.com/blog/…
  • 谢谢。该链接包含一些有用的信息。我猜 docblock 可以为 PhpStorm 自动补全提供解决方案,我想我不能指望 PHP 具有类似 Java 的类型严格性。
  • 当然可以:if (!($user instanceof SiteUserInterface)) throw new Exception(...)

标签: php symfony type-hinting


【解决方案1】:

如果您需要更具体的类,其中包含 UserInterface 缺少的那些方法,您应该使用它

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

那么就不需要添加docblock了。

【讨论】:

    猜你喜欢
    • 2020-08-12
    • 2019-01-15
    • 2016-06-10
    • 2020-08-28
    • 2012-01-17
    • 2021-05-11
    • 2018-08-23
    • 2012-10-15
    • 2022-01-05
    相关资源
    最近更新 更多