【问题标题】:Zend Framework 2 – type hinting in constructor – IDE complains about typeZend Framework 2 – 构造函数中的类型提示 – IDE 抱怨类型
【发布时间】:2016-01-08 21:12:19
【问题描述】:

在 Zend Framework 2 模块中,我使用闭包作为工厂:

'controllers' => [
    'factories' => [
        'ZendSkeletonModule\Controller\Skeleton' => function(AbstractPluginManager $pm) {
            return new Controller\SkeletonController($pm->getServiceLocator()->get('Doctrine\ORM\EntityManager'));
        },
    ],
],

虽然这没有任何问题,但我的 IDE (PHP Storm) 在$pm->getServiceLocator()->get('Doctrine\ORM\EntityManager') 抱怨以下消息:

预期 \Doctrine\ORM\EntityManagerInterface,得到数组|对象。
调用参数类型与声明不兼容。

那是因为在控制器中,我使用Doctrine\ORM\EntityManagerInterface 作为类型提示,我明白了。

但是为什么 PHP Storm 会抱怨,我在这里没有发现任何问题?另外,代码工作正常,所以我有点困惑。我是否需要添加某种特殊注释或其他内容来“帮助”IDE?

【问题讨论】:

    标签: php zend-framework2 phpstorm type-hinting


    【解决方案1】:

    将 EntityManager 分配给一个带有 PhpStorm 静态分析可以使用的注释的变量。 get 方法本身是不透明的:

    use Doctrine\ORM\EntityManager;
    // snip
    'controllers' => [
        'factories' => [
            'ZendSkeletonModule\Controller\Skeleton' => function(AbstractPluginManager $pm) {
                /** @var EntityManager $entityManager */
                $entityManager = $pm->getServiceLocator()->get(EntityManager::class);
                return new Controller\SkeletonController($entityManager);
            },
        ],
    ],
    

    一些额外的建议:

    1. 与其使用闭包,不如使用具体的工厂类。这是因为闭包不能被操作码缓存,而且你的配置数组如果包含闭包也不能被缓存。

    2. 一件小事,但假设 PHP 5.5+,考虑使用 \Doctrine\ORM\EntityManager::class 就像我在上面的示例中所做的那样,而不是 ServiceLocator 上的 get 方法的字符串文字。

    【讨论】:

    • PhpStorm 在PHPSTORM_META\$STATIC_METHOD_TYPES 内部也支持这样的工厂方法(参见confluence.jetbrains.com/display/PhpStorm/…
    • 谢谢你!你真的帮我解决了这个问题——它困扰了我好几个星期。您的其他提示也很棒,再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 2015-10-11
    相关资源
    最近更新 更多