tp6中的依赖注入,满射注入

容器是用来更方便的管理类依赖及运行依赖注入的工具。
依赖注入其实本质上是指在构造函数中对其他需要使用的类迅速实例化。
依赖注入的类统一由容器进行管理,你可以随时绑定类到容器中,支持多种绑定方式。
例如我们有个 Settings类,现在绑定到容器中

    // 绑定类库标识
bind('settings','app\admin\controller\Settings');

或者:
bind('settings',Settings::class);

或者:
Container::getInstance()->bind('settings', Upgrade::class)

调用方式:
halt(app('settings')->upgradeTask($this->request));
或:
Container::getInstance()->make('settings')->upgradeTask($this->request)

在容器中他会自动调用

/**
     * 获取当前容器的实例(单例)
     * @access public
     * @return static
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }

        if (static::$instance instanceof Closure) {
            return (static::$instance)();
        }

        return static::$instance;
    }

然后我们用app()助手函数直接获取类中方法upgradeTask:

app('settings')->upgradeTask($this->request)

绑定闭包

可以绑定一个闭包到容器中

bind('sayHello', function ($name) {
    return 'hello,' . $name;
});

绑定实例

也可以直接绑定一个类的实例

$cache = new think\Cache;
// 绑定类实例
bind('cache', $cache);

绑定至接口实现

对于依赖注入使用接口类的情况,我们需要告诉系统使用哪个具体的接口实现类来进行注入,这个使用可以把某个类绑定到接口

// 绑定think\LoggerInterface接口实现到think\Log
bind('think\LoggerInterface','think\Log');
发布了124 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_42433970/article/details/102969401
今日推荐