ServiceProvider 的方式接入到 Laravel
有些朋友说,看了很多资料也不太明白 ServiceProvider
到底是干嘛用的,今天我试图用大白话聊一聊 ServiceProvier
。
设想一个场景,你写了一个CMS,那自然就包含了路由、配置、数据库迁移、帮助函数或类等。如果你要用 ServiceProvider
的方式接入到 Laravel
,应该怎么办?
我们在上述用了 “接入到 Laravel
” 这样的字眼,本质上就是把这些信息告诉 Kernel
。如何告诉呢?使用 Laravel
提供的 ServiceProvider
,默认 ServiceProvider
要提供两个方法 register
和 boot
。
register
就是把实例化对象的方式注册到容器中。
boot
就是做一些把配置文件推到项目根目录下的 config
目录下面,加载配置到 Kernel
或加载路由等动作。
顺序是先 register
再 boot
。
源码验证
这点可以在源码中得到佐证:
干说也无趣,分析一个开源的 ServiceProvider
更直观。
https://github.com/tymondesig…
开源组件的 ServiceProvider
看这个开源组件的 ServiceProvider
是怎么写的:
https://github.com/tymondesig…
1 2 3 4 5 6 7 8 | 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
。
看它的基类 https://github.com/tymondesig…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 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
能识别的方式接入进去。
以上就是Laravel中ServiceProvider使用示例详解的详细内容,更多关于Laravel ServiceProvider的资料请关注IT俱乐部其它相关文章!