Laravel中ServiceProvider使用場(chǎng)景示例詳解
有些朋友說(shuō),看了很多資料也不太明白 ServiceProvider 到底是干嘛用的,今天我試圖用大白話(huà)聊一聊 ServiceProvier。
設(shè)想一個(gè)場(chǎng)景,你寫(xiě)了一個(gè)CMS,那自然就包含了路由、配置、數(shù)據(jù)庫(kù)遷移、幫助函數(shù)或類(lèi)等。如果你要用 ServiceProvider 的方式接入到 Laravel,應(yīng)該怎么辦?
我們?cè)谏鲜鲇昧?“接入到 Laravel” 這樣的字眼,本質(zhì)上就是把這些信息告訴 Kernel。如何告訴呢?使用 Laravel 提供的 ServiceProvider,默認(rèn) ServiceProvider 要提供兩個(gè)方法 register 和 boot。
register 就是把實(shí)例化對(duì)象的方式注冊(cè)到容器中。
boot 就是做一些把配置文件推到項(xiàng)目根目錄下的 config 目錄下面,加載配置到 Kernel 或加載路由等動(dòng)作。
順序是先 register 再 boot。
源碼驗(yàn)證這點(diǎn)可以在源碼中得到佐證:
干說(shuō)也無(wú)趣,分析一個(gè)開(kāi)源的 ServiceProvider 更直觀。
https://github.com/tymondesig...
開(kāi)源組件的 ServiceProvider看這個(gè)開(kāi)源組件的 ServiceProvider 是怎么寫(xiě)的:
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();}非常簡(jiǎn)單,把配置文件推到 config 目錄下,加載配置文件,給中間件設(shè)置一個(gè)別名,擴(kuò)展一下 AuthGuard。
看它的基類(lèi) 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')); });}本質(zhì)上就是注冊(cè)一些實(shí)例化對(duì)象的方法到容器,用于后來(lái)的自動(dòng)裝配,解決注入的依賴(lài)問(wèn)題。
所以 ServiceProvider 本質(zhì)上是個(gè)啥?它就是提供接入 Laravel 的方式,它本身并不實(shí)現(xiàn)具體功能,只是將你寫(xiě)好的功能以 Laravel 能識(shí)別的方式接入進(jìn)去。
以上就是Laravel中ServiceProvider使用示例詳解的詳細(xì)內(nèi)容,更多關(guān)于Laravel ServiceProvider的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
