serviceprovider 的方式接入到 laravel
有些朋友说,看了很多资料也不太明白 serviceprovider 到底是干嘛用的,今天我试图用大白话聊一聊 serviceprovier。
设想一个场景,你写了一个cms,那自然就包含了路由、配置、数据库迁移、帮助函数或类等。如果你要用 serviceprovider 的方式接入到 laravel,应该怎么办?
我们在上述用了 “接入到 laravel” 这样的字眼,本质上就是把这些信息告诉 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 目录下,加载配置文件,给中间件设置一个别名,扩展一下 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 能识别的方式接入进去。
以上就是laravel中serviceprovider使用示例详解的详细内容,更多关于laravel serviceprovider的资料请关注代码网其它相关文章!
发表评论