色综合图-色综合图片-色综合图片二区150p-色综合图区-玖玖国产精品视频-玖玖香蕉视频

您的位置:首頁技術(shù)文章
文章詳情頁

Laravel中ServiceProvider使用場景示例詳解

瀏覽:3日期:2022-06-13 18:59:05
目錄ServiceProvider 的方式接入到 Laravel源碼驗證開源組件的 ServiceProviderServiceProvider 的方式接入到 Laravel

有些朋友說,看了很多資料也不太明白 ServiceProvider 到底是干嘛用的,今天我試圖用大白話聊一聊 ServiceProvier。

設(shè)想一個場景,你寫了一個CMS,那自然就包含了路由、配置、數(shù)據(jù)庫遷移、幫助函數(shù)或類等。如果你要用 ServiceProvider 的方式接入到 Laravel,應該怎么辦?

我們在上述用了 “接入到 Laravel” 這樣的字眼,本質(zhì)上就是把這些信息告訴 Kernel。如何告訴呢?使用 Laravel 提供的 ServiceProvider,默認 ServiceProvider 要提供兩個方法 register 和 boot。

register 就是把實例化對象的方式注冊到容器中。

boot 就是做一些把配置文件推到項目根目錄下的 config 目錄下面,加載配置到 Kernel 或加載路由等動作。

順序是先 register 再 boot。

源碼驗證

這點可以在源碼中得到佐證:

干說也無趣,分析一個開源的 ServiceProvider 更直觀。

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

開源組件的 ServiceProvider

看這個開源組件的 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 目錄下,加載配置文件,給中間件設(shè)置一個別名,擴展一下 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')); });}

本質(zhì)上就是注冊一些實例化對象的方法到容器,用于后來的自動裝配,解決注入的依賴問題。

所以 ServiceProvider 本質(zhì)上是個啥?它就是提供接入 Laravel 的方式,它本身并不實現(xiàn)具體功能,只是將你寫好的功能以 Laravel 能識別的方式接入進去。

以上就是Laravel中ServiceProvider使用示例詳解的詳細內(nèi)容,更多關(guān)于Laravel ServiceProvider的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標簽: PHP
主站蜘蛛池模板: 欧美一级片在线免费观看 | 国产亚洲图片 | a级片在线免费观看 | 一级黄视频 | 国产玖玖视频 | 国产成人精品久久综合 | 大伊香蕉精品视频在线观看 | 三级黄色毛片视频 | 久久成人动漫 | 亚洲精品久久久久网站 | 手机在线日韩高清理论片 | 亚洲欧美自拍视频 | 国产午夜亚洲精品第一区 | 欧美在线观看一区 | 伊大人香蕉久久网 | 亚洲第三区 | 99久久视频| 日本一区二区三区高清福利视频 | 在线观看 一区 | 99香蕉网 | 99久久九九| 日本九九视频 | 福利片成人午夜在线 | 美女网站在线 | 久草视频国产 | 日本韩国欧美一区 | 综合欧美一区二区三区 | 成年人三级视频 | www.a级片| 亚洲精品日本高清中文字幕 | 亚洲精品视频久久久 | 亚洲一区中文字幕在线 | 一级做a爰片久久毛片美女 一级做a爰片久久毛片免费看 | 欧美特黄一级aa毛片 | 欧美精品久久 | 九九re6精品视频在线观看 | 亚洲男人的天堂在线 | 99久久国产综合精品1尤物 | 97精品国产高清在线看入口 | 美女超爽久久久久网站 | 中文字幕在线观看一区二区 |