当前位置: 代码网 > it编程>编程语言>Php > Laravel中ServiceProvider使用场景示例详解

Laravel中ServiceProvider使用场景示例详解

2024年05月18日 Php 我要评论
serviceprovider的方式接入到laravel有些朋友说,看了很多资料也不太明白serviceprovider到底是干嘛用的,今天我试图用大白话聊一聊serviceprovier。设想一个场

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的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com