protected $bootstrappers = [
....
\Illuminate\Foundation\Bootstrap\RegisterProviders::class,
\Illuminate\Foundation\Bootstrap\BootProviders::class,
];
分别对应:
1. $app->registerConfiguredProviders();
通过ProviderRepository实例的load方法调用$this->app->register($provider);
public function register($provider, $force = false)
{
....
$provider->register();
....
if ($this->isBooted()) {//默认false,猜测此处在注册reffer providers时为true
$this->bootProvider($provider);
}
return $provider;
}
//此处$this指向RouteServiceProvider
public function register()
{
//赋值$this->bootedCallbacks
$this->booted(function () {
$this->setRootControllerNamespace();
if ($this->routesAreCached()) {
$this->loadCachedRoutes();
} else {
$this->loadRoutes();
$this->app->booted(function () {
$this->app['router']->getRoutes()->refreshNameLookups();
$this->app['router']->getRoutes()->refreshActionLookups();
});
}
});
}
2. $app->boot();
public function boot()
{
if ($this->isBooted()) {
return;
}
$this->fireAppCallbacks($this->bootingCallbacks);
array_walk($this->serviceProviders, function ($p) {
$this->bootProvider($p);
});
$this->booted = true;
$this->fireAppCallbacks($this->bootedCallbacks);
}
protected function bootProvider(ServiceProvider $provider)
{
$provider->callBootingCallbacks();
if (method_exists($provider, 'boot')) {
$this->call([$provider, 'boot']);
}
$provider->callBootedCallbacks();
}
//此处$this指向RouteServiceProvider
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
//赋值$this->loadRoutesUsing
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
function () {
$this->setRootControllerNamespace();
if ($this->routesAreCached()) {
$this->loadCachedRoutes();
} else {
$this->loadRoutes();
$this->app->booted(function () {
$this->app['router']->getRoutes()->refreshNameLookups();
$this->app['router']->getRoutes()->refreshActionLookups();
});
}
});
protected function loadRoutes()
{
if (! is_null($this->loadRoutesUsing)) {
$this->app->call($this->loadRoutesUsing);
} elseif (method_exists($this, 'map')) {
$this->app->call([$this, 'map']);
}
}
以上说明,Route::middleware('web')->group(base_path('routes/web.php'));
是在provider booted之后,app booted之前执行。
文章详细阐述了在Laravel框架中,从`$bootstrappers`数组开始,如何执行`registerProviders`和`bootProviders`,进而触发`ServiceProvider`的注册和启动过程。重点讨论了`RouteServiceProvider`中的`boot`方法,包括`RateLimiter`的设置和`web`、`api`中间件的路由分组。整个过程揭示了Laravel应用启动时路由加载的顺序和时机。
255

被折叠的 条评论
为什么被折叠?



