BootProviders
bootstrap()
//class BootProviders
public function bootstrap(Application $app)
{
$app->boot();
}
//class Application
public function boot()
{
...
//执行存储在bootingCallbacks的匿名函数,当前bootingCallback为空数组
$this->fireAppCallbacks($this->bootingCallbacks);//$this->bootingCallbacks = []
//遍历serviceProviders,并执行bootProvider()
array_walk($this->serviceProviders, function ($p) {
$this->bootProvider($p);
});
//更新booted属性
$this->booted = true;
//执行BootProvider执行过程中添加在bootedCallbacks内的匿名函数
$this->fireAppCallbacks($this->bootedCallbacks);
}
$this->bootProvider()
//class Application
protected function bootProvider(ServiceProvider $provider)
{
if (method_exists($provider, 'boot')) {
return $this->call([$provider, 'boot']);
}
}
- call()
public function call($callback, array $parameters = [], $defaultMethod = null)
{
return BoundMethod::call($this, $callback, $parameters, $defaultMethod);
}
- BoundMethods::call()
//class BoundMethods
public static function call($container, $callback, array $parameters = [], $defaultMethod = null)
{
...
return static::callBoundMethod($container, $callback, function () use ($container, $callback, $parameters) {
return call_user_func_array(
//static::getMethodDependencies()获取实例依赖参数,BootProvider执行注册服务的boot()方法无需参数,故return []
$callback, static::getMethodDependencies($container, $callback, $parameters)
);
});
}
- BoundMethods::callBoundMethod()
protected static function callBoundMethod($container, $callback, $default)
{
...
//当前$callback数据类型为数组,分别存储[$object,'function'],normalizeMethod()将其转换为'class@function'字符串
$method = static::normalizeMethod($callback);
//当前MethondBindings = [];
if ($container->hasMethodBinding($method)) {
return $container->callMethodBinding($method, $callback[0]);
}
//执行匿名函数,即执行当前$provider->boot()
return $default instanceof Closure ? $default() : $default;
}
总结
服务提供者的注册及启动核心方法是当前服务的boot(),任务量实在太大,慢慢看吧!先看一下我们使用框架中常见的服务列表吧,有时间对感兴趣的看一下吧!
array:20 [▼
0 => EventServiceProvider {#6 ▶}
1 => LogServiceProvider {#8 ▶}
2 => RoutingServiceProvider {#10 ▶}
3 => AuthServiceProvider {#41 ▶}
4 => CookieServiceProvider {#37 ▶}
5 => DatabaseServiceProvider {#51 ▶}
6 => EncryptionServiceProvider {#58 ▶}
7 => FilesystemServiceProvider {#60 ▶}
8 => FormRequestServiceProvider {#66 ▶}
9 => FoundationServiceProvider {#65 ▶}
10 => NotificationServiceProvider {#68 ▶}
11 => PaginationServiceProvider {#70 ▶}
12 => SessionServiceProvider {#74 ▶}
13 => ViewServiceProvider {#78 ▶}
14 => TrustedProxyServiceProvider {#82 ▶}
15 => ServiceProvider {#83 ▶}
16 => AppServiceProvider {#84 ▶}
17 => AuthServiceProvider {#85 ▶}
18 => EventServiceProvider {#86 ▶}
19 => RouteServiceProvider {#87 ▶}
]