Laravel配置Passport时调用routesAreCached()提示方法未定义
问题描述
参照Laravel 9.x官方文档为Laravel应用配置Passport组件,在执行Passport::routes()调用前的路由缓存校验步骤时,VSCode抛出如下错误提示:
undefined method: routesAreCached()
溯源到框架抽象基类ServiceProvider.php文件时,发现框架原生代码调用$this->app->routesAreCached()并未出现运行异常。以下是项目中App\Providers\AuthServiceProvider.php的代码内容:
<?php namespace App\Providers; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Gate; use Laravel\Passport\Passport; class AuthServiceProvider extends ServiceProvider { /** * The model to policy mappings for the application. * * @var array<class-string, class-string> */ protected $policies = [ // 'App\Models\Model' => 'App\Policies\ModelPolicy', ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); /** * This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens: * */ if (! $this->app->routesAreCached()) { // 该行抛出编辑器报错 Passport::routes(); } } }
报错原因
这是VSCode中PHP静态分析插件(最常见的是PHP Intelephense)的误报,不属于代码运行层面的错误。$this->app指向的是Laravel服务容器实例,其类型声明为接口Illuminate\Contracts\Foundation\Application,而routesAreCached()是接口的实际实现类Illuminate\Foundation\Application中定义的公开方法,框架内部所有自带服务提供者都用相同写法判断路由缓存状态,代码实际运行时不会触发任何异常。
解决方案
可根据需求任选一种处理方式:
- 直接忽略编辑器的错误提示:现有写法完全符合框架规范,执行路由缓存、Passport路由注册等逻辑都能正常运行,不会出现报错。
- 调整写法消除编辑器提示:可以改用全局
app()助手函数调用判断方法,或者添加注释让静态分析插件跳过该行检查,示例代码如下:
// 写法1:使用app()助手函数调用 if (! app()->routesAreCached()) { Passport::routes(); } // 写法2:添加注释跳过静态分析检查 /** @noinspection PhpUndefinedMethodInspection */ if (! $this->app->routesAreCached()) { Passport::routes(); }
内容的提问来源于stack exchange,提问作者Fear4Haunt
相关产品推荐
相关产品推荐

