是否可以覆盖全局函数的 phpdoc return 类型?

Is it possible to override the phpdoc return type of a global function?

我想覆盖全局 response function as I've created a package which overrides the response class returned. A Service Provider is extending the response class which will be returned instead the default \Illuminate\Http\Response. This is all working and also recognized when generating IDE files via the Laravel IDE helper 的 return 类型。

我的问题是只有上述函数的 第一次调用 列出了扩展 class 方法。否则它会列出来自 phpdocs 引用的 \Illuminate\Contracts\Routing\ResponseFactory 接口的方法,这是我想要覆盖的接口。我的界面只是将 return 类型更改为我的包的响应 class:

<?php

namespace My\Package;

use Illuminate\Contracts\Routing\ResponseFactory as BaseResponseFactory;

interface ResponseFactory extends BaseResponseFactory
{
    /**
     * Return a new response from the application.
     *
     * @param  string $content
     * @param  int $status
     * @param  array $headers
     *
     * @return \My\Package\Response
     */
    public function make($content = '', $status = 200, array $headers = []);

    /**
     * Return a new view response from the application.
     *
     * @param  string $view
     * @param  array $data
     * @param  int $status
     * @param  array $headers
     *
     * @return \My\Package\Response
     */
    public function view($view, $data = [], $status = 200, array $headers = []);
}

我怎样才能做到这一点?

实现此目的的唯一方法是创建一个自定义 app/helpers.php 文件,并在其中用您想要的 @return 类型覆盖整个 Laravel response 函数.如果您通过 Composer 使用自动加载,则添加

"autoload": {
    "files": ["app/helpers.php"]
}

不会工作,因为Laravels 辅助函数首先加载。 您必须在 index.php 之前手动要求文件 autoload.php:

require __DIR__ .'/../app/helpers.php';
require __DIR__.'/../vendor/autoload.php';

但请注意,如果不调整 phpunit.xml 以包含自定义 bootstrap 文件,这将破坏您的单元测试!

或者,有一个 composer 插件(未测试)处理优先级问题:https://github.com/funkjedi/composer-include-files

总的来说,我认为这样做 只是为了 IDE 合规性 这太老套了,根本不是优势。