laravel 注册服务提供者

版权声明:转载请注明博主地址 https://blog.csdn.net/weixin_43885417/article/details/85016044

laravel所有的服务提供者都是通过配置文件,config/app.php中进行注册,该文件包含了一个列出所有服务提供者名字的provider数组。
如果要注册你自己的服务提供者,只需往数组里追加到该数组:

'providers' => [
    // 其它服务提供者
    App\Providers\ComposerServiceProvider::class,
],

当然,你可以设置为延迟加载服务提供者,等你真的需要时候,再去加载。
设置defer属性为true,并定义一个provides方法。该方法返回该提供者注册的服务容器绑定:

<?php

namespace App\Providers;

use Riak\Connection;
use Illuminate\Support\ServiceProvider;

class RiakServiceProvider extends ServiceProvider{
    /**
     * 服务提供者加是否延迟加载.
     *
     * @var bool
     */
    protected $defer = true;

    /**
     * 注册服务提供者
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Connection::class, function ($app) {
            return new Connection($app['config']['riak']);
        });
    }

    /**
     * 获取由提供者提供的服务.
     *
     * @return array
     */
    public function provides()
    {
        return [Connection::class];
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_43885417/article/details/85016044
今日推荐