PhpStorm - 关于 Laravel 门面的一些警告

PhpStorm - Some warnings on Laravel facades

  1. 我正确使用了 Laravel 的外观,PhpStorm 给我警告,这是为什么?

  2. 在图像上我指出 "x" 一些...数据类型?在我使用的功能中,为什么我有这些?如何删除它们?

将外观与 Laravel

一起使用

:

You're not using facades. You've imported the classes, and on the first, Categories, the IDE is telling you that the get method is not a static method.

只需导入外观(如果存在)。

参见documentation on Facades to learn more on how to use the available facades and how to define your own

外观 class 应如下所示:

use Illuminate\Support\Facades\Facade;

class Cache extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() 
    { 
        return 'cache';
    }
}

其中 'cache' 字符串是 service container binding and defined in a service provider 的名称,类似这样:

use App\Cache\MyCache;
use Illuminate\Support\ServiceProvider;

class CacheServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('cache', function ($app) {
            return new MyCache();
        });
    }
}

修复 Facades 的警告

话虽这么说,我已经厌倦了警告和缺少的自动完成功能,并用 facades 突出显示,所以我也搜索了一种方法来解决这些问题。

我发现 laravel-ide-helper 添加了 Laravel CLI 命令生成 php 文件,这些文件仅供您的 IDE.

解析

Install

Require this package with composer using the following command:

composer require barryvdh/laravel-ide-helper

After updating composer, add the service provider to the providers array in config/app.php

Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class, To install this package on only development systems, add the --dev flag to your composer command:

composer require --dev barryvdh/laravel-ide-helper

In Laravel, instead of adding the service provider in the config/app.php file, you can add the following code to your app/Providers/AppServiceProvider.php file, within the register() method:

public function register()
{
    if ($this->app->environment() !== 'production') {
        $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
    }
    // ...
}

This will allow your application to load the Laravel IDE Helper on non-production enviroments.

Automatic phpDoc generation for Laravel Facades

You can now re-generate the docs yourself (for future updates)

php artisan ide-helper:generate

Note: bootstrap/compiled.php has to be cleared first, so run php artisan clear-compiled before generating (and php artisan optimize after).

You can configure your composer.json to do this after each commit:

"scripts":{
    "post-update-cmd": [
        "Illuminate\Foundation\ComposerScripts::postUpdate",
        "php artisan ide-helper:generate",
        "php artisan ide-helper:meta",
        "php artisan optimize"
    ]
},

将生成 .phpstorm.meta.php_ide_helper.php 文件,应将其添加到您的 .gitignore 中,因为您不想提交这些文件。