当前位置: 首页 > 后端技术 > PHP

关于Laravel中的ServiceProvider

时间:2023-03-30 00:17:56 PHP

,有小伙伴表示看了很多资料,还是不太明白ServiceProvider是干什么用的。今天尝试用大白话来说说ServiceProvier。想象一个场景,你写一个CMS,自然包括路由、配置、数据库迁移、辅助函数或类等,如果你想使用ServiceProvider连接Laravel,你应该怎么做?我们在上面使用了“连接到Laravel”这个词,它本质上是告诉内核这个信息。怎么说?使用Laravel提供的ServiceProvider,默认的ServiceProvider提供了register和boot两种方法。注册就是将实例化对象注册到容器中的方式。boot就是做一些动作,比如将配置文件推送到项目根目录下的config目录,加载配置到Kernel或者加载路由。顺序是先注册后开机。这在源码中可以得到印证:讲起来很无聊,分析一个开源的ServiceProvider更直观。https://github.com/tymondesig...看看这个开源组件的ServiceProvider是怎么写的:https://github.com/tymondesig...publicfunctionboot(){$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...publicfunctionregister(){$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');}保护函数registerNamshiProvider(){$this->app->singleton('tymon.jwt.provider.jwt.namshi',function($app){returnnewNamshi(newJWS(['typ'=>'JWT','alg'=>$this->config('algo')]),$this->config('secret'),$this->config('algo'),$this->config('keys'));});}/***注册绑定对于LcobucciJWT提供商。**@returnvoid*/protectedfunctionregisterLcobucciProvider(){$this->app->singleton('tymon.jwt.provider.jwt.lcobucci',function($app){返回新Lcobucci(newJWTBuilder(),newJWTParser(),$this->config('secret'),$this->config('algo'),$this->config('keys'));});}本质上就是注册一些方法将对象实例化到容器中,供后期自动组装,解决注入的依赖问题。那么ServiceProvider本质上是什么?它提供了一种访问Laravel的方法。它本身并不会实现具体的功能,只是将你编写的功能以Laravel可以识别的方式连接起来。