Laravel Service Provider设置延迟加载后注册失败
问题
在参考网上示例,尝试创建service provider的时候,第一次尝试成功运行;然后修改其 $defer 属性为true再注释掉后,service provider始终无法加载成功。
定位&解决过程
验证新建的service provider本身是否有问题
\App\Providers\AppServiceProvider是系统默认会加载的,可以在其register函数中,链式加载新建的service providerpublic function register() { $this->app->register(ExampleServiceProvider::class); }试验后,发现程序正常运行,所以基本确认是注册在
config/app.php中的ExampleServiceProvider没有生效。研究service provider加载的源码
通过
Illuminate\Foundation\Application源码找到registerConfiguredProviders方法:(new ProviderRepository($this, new Filesystem, $this->getCachedServicesPath())) ->load($providers->collapse()->toArray());Laravel是通过这个方法读取
config/app.php中的providers内容并加载到ProviderRepository中。根据
$this->getCachedServicesPath()可以看出,这里是有缓存的。Laravel会根据
bootstrap/cache/services.php缓存文件的内容去加载service provider。程序员生涯两座大山:缓存 & 命名
解决方法
更改defer属性后,需要执行 php artisan clear-compiled 和 php artisan optimize 来更新service provider的缓存。