laravel里所谓的provider服务提供者,其实是对某一类功能进行整合,与做一些使用前的初始化引导工作。laravel里的服务提供者也分为,系统核心服务提供者、与一般系统服务提供者。例如上一篇博文里介绍的,最早在application中进行注册的event、log、routing这些就是系统的核心服务,laravel的初始化需要他们。那么现在就先来看一下provider的运行流程。
1 protected function registerBaseServiceProviders() 2 { 3 $this->register(new EventServiceProvider($this)); 4 5 $this->register(new LogServiceProvider($this)); 6 7 $this->register(new RoutingServiceProvider($this)); 8 }
其他的serviceProvider则是指config/app.php中providers数组所配置的provider了,基本都是些laravel系统提供的工具型provider
1 'providers' => [ 2 3 /* 4 * Laravel Framework Service Providers... 5 */ 6 Illuminate\Auth\AuthServiceProvider::class, 7 Illuminate\Broadcasting\BroadcastServiceProvider::class, 8 Illuminate\Bus\BusServiceProvider::class, 9 Illuminate\Cache\CacheServiceProvider::class, 10 Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, 11 Illuminate\Cookie\CookieServiceProvider::class, 12 Illuminate\Database\DatabaseServiceProvider::class, 13 Illuminate\Encryption\EncryptionServiceProvider::class, 14 Illuminate\Filesystem\FilesystemServiceProvider::class, 15 Illuminate\Foundation\Providers\FoundationServiceProvider::class, 16 Illuminate\Hashing\HashServiceProvider::class, 17 Illuminate\Mail\MailServiceProvider::class, 18 Illuminate\Notifications\NotificationServiceProvider::class, 19 Illuminate\Pagination\PaginationServiceProvider::class, 20 Illuminate\Pipeline\PipelineServiceProvider::class, 21 Illuminate\Queue\QueueServiceProvider::class, 22 Illuminate\Redis\RedisServiceProvider::class, 23 Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, 24 Illuminate\Session\SessionServiceProvider::class, 25 Illuminate\Translation\TranslationServiceProvider::class, 26 Illuminate\Validation\ValidationServiceProvider::class, 27 Illuminate\View\ViewServiceProvider::class, 28 //Maatwebsite\Excel\ExcelServiceProvider::class, 这个是我自己测试的时候加的 29 30 /* 31 * Package Service Providers... 32 */ 33 34 /* 35 * Application Service Providers... 36 */ 37 App\Providers\AppServiceProvider::class, 38 App\Providers\AuthServiceProvider::class, 39 // App\Providers\BroadcastServiceProvider::class, 40 App\Providers\EventServiceProvider::class, 41 App\Providers\RouteServiceProvider::class, 42 43 ],
那么这些配置中的provider会在什么时候加载呢?上一篇博文中介绍的当$kernel对象通过handle方法传入request时,会执行sendRequestThroughRouter方法,这个方法中的bootstrap方法会加载laravel系统初始化所需的对象并运行,其中RegisterProviders类便是用来注册刚刚config文件内所记录的provider的
1 public function bootstrap() 2 { 3 if (! $this->app->hasBeenBootstrapped()) { 4 $this->app->bootstrapWith($this->bootstrappers()); 5 } 6 } 7 8 protected $bootstrappers = [ 9 \Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables::class, 10 \Illuminate\Foundation\Bootstrap\LoadConfiguration::class, 11 \Illuminate\Foundation\Bootstrap\HandleExceptions::class, 12 //注册facade门面类 13 \Illuminate\Foundation\Bootstrap\RegisterFacades::class, 14 //注册provider 15 \Illuminate\Foundation\Bootstrap\RegisterProviders::class, 16 //引导provider执行其中boot方法内的代码 17 \Illuminate\Foundation\Bootstrap\Boot