關於Laravel中的ServiceProvider

有些朋友說,看了不少資料也不太明白 ServiceProvider 究竟是幹嗎用的,今天我試圖用大白話聊一聊 ServiceProvierphp

設想一個場景,你寫了一個CMS,那天然就包含了路由、配置、數據庫遷移、幫助函數或類等。若是你要用 ServiceProvider 的方式接入到 Laravel,應該怎麼辦?git

咱們在上述用了 「接入到 Laravel」 這樣的字眼,本質上就是把這些信息告訴 Kernel。如何告訴呢?使用 Laravel 提供的 ServiceProvider,默認 ServiceProvider 要提供兩個方法 registerbootgithub

register 就是把實例化對象的方式註冊到容器中。
boot 就是作一些把配置文件推到項目根目錄下的 config 目錄下面,加載配置到 Kernel 或加載路由等動做。數據庫

順序是先 registerboot。這點能夠在源碼中獲得佐證:app

image.png

幹說也無趣,分析一個開源的 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 目錄下,加載配置文件,給中間件設置一個別名,擴展一下 AuthGuardspa

看它的基類 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 能識別的方式接入進去。

相關文章
相關標籤/搜索