有些朋友说,看了不少资料也不太明白 ServiceProvider
究竟是干吗用的,今天我试图用大白话聊一聊 ServiceProvier
。php
设想一个场景,你写了一个CMS,那天然就包含了路由、配置、数据库迁移、帮助函数或类等。若是你要用 ServiceProvider
的方式接入到 Laravel
,应该怎么办?git
咱们在上述用了 “接入到 Laravel
” 这样的字眼,本质上就是把这些信息告诉 Kernel
。如何告诉呢?使用 Laravel
提供的 ServiceProvider
,默认 ServiceProvider
要提供两个方法 register
和 boot
。github
register
就是把实例化对象的方式注册到容器中。boot
就是作一些把配置文件推到项目根目录下的 config
目录下面,加载配置到 Kernel
或加载路由等动做。数据库
顺序是先 register
再 boot
。这点能够在源码中获得佐证:app
干说也无趣,分析一个开源的 ServiceProvider
更直观。ide
https://github.com/tymondesig...函数
看这个开源组件的 ServiceProvider
是怎么写的:ui
https://github.com/tymondesig...this
public function boot() { $path = realpath(__DIR__.'/../../config/config.php'); $this->publishes([$path => config_path('jwt.php')], 'config'); $this->mergeConfigFrom($path, 'jwt'); $this->aliasMiddleware(); $this->extendAuthGuard(); }
很是简单,把配置文件推到 config
目录下,加载配置文件,给中间件设置一个别名,扩展一下 AuthGuard
。spa
看它的基类 https://github.com/tymondesig...
public function register() { $this->registerAliases(); $this->registerJWTProvider(); $this->registerAuthProvider(); $this->registerStorageProvider(); $this->registerJWTBlacklist(); $this->registerManager(); $this->registerTokenParser(); $this->registerJWT(); $this->registerJWTAuth(); $this->registerPayloadValidator(); $this->registerClaimFactory(); $this->registerPayloadFactory(); $this->registerJWTCommand(); $this->commands('tymon.jwt.secret'); } protected function registerNamshiProvider() { $this->app->singleton('tymon.jwt.provider.jwt.namshi', function ($app) { return new Namshi( new JWS(['typ' => 'JWT', 'alg' => $this->config('algo')]), $this->config('secret'), $this->config('algo'), $this->config('keys') ); }); } /** * Register the bindings for the Lcobucci JWT provider. * * @return void */ protected function registerLcobucciProvider() { $this->app->singleton('tymon.jwt.provider.jwt.lcobucci', function ($app) { return new Lcobucci( new JWTBuilder(), new JWTParser(), $this->config('secret'), $this->config('algo'), $this->config('keys') ); }); }
本质上就是注册一些实例化对象的方法到容器,用于后来的自动装配,解决注入的依赖问题。
因此 ServiceProvider
本质上是个啥?它就是提供接入 Laravel
的方式,它自己并不实现具体功能,只是将你写好的功能以 Laravel
能识别的方式接入进去。