有些敌人说,看了很多材料也不太明确 ServiceProvider 到底是干嘛用的,明天我试图用大白话聊一聊 ServiceProvier

构想一个场景,你写了一个CMS,那天然就蕴含了路由、配置、数据库迁徙、帮忙函数或类等。如果你要用 ServiceProvider 的形式接入到 Laravel,应该怎么办?

咱们在上述用了 “接入到 Laravel” 这样的字眼,实质上就是把这些信息通知 Kernel。如何通知呢?应用 Laravel 提供的 ServiceProvider,默认 ServiceProvider 要提供两个办法 registerboot

register 就是把实例化对象的形式注册到容器中。
boot 就是做一些把配置文件推到我的项目根目录下的 config 目录上面,加载配置到 Kernel 或加载路由等动作。

程序是先 registerboot。这点能够在源码中失去佐证:

干说也无趣,剖析一个开源的 ServiceProvider 更直观。

https://github.com/tymondesig...

看这个开源组件的 ServiceProvider 是怎么写的:

https://github.com/tymondesig...

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...

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 能辨认的形式接入进去。