PHP之依赖注入

依赖注入

解释

依赖注入 (DI)其实本质上是指对类的依赖通过构造器完成自动注入通俗来说,就是你当前操作一个类,但是这个类的某些方法或者功能不是单单只靠这个类就能完成的,而是要借助另一个类的才能完成的最直接的标志就是传参数据为对象的时候。严格来说,你想在另一个类中操作另一个类,这两个类之间形成了相互依赖关系,传参的方式叫注入

简单的依赖注入

  • 就是通过构造函数去注入
php 复制代码
<?php

class container
{
    private $adapter;

    public function __construct(adapter $adapter)
    {
        $this->adapter = $adapter;
    }
}

高阶的依赖注入

php 复制代码
<?php

class container
{
    public
        $instance = [];

    public
    function __set($name, $value)
    {
        $this->instance[$name] = $value;
    }
}

$container = new container();
$container->adapter = new adapter();

依赖注入的容器应用

php 复制代码
<?php

class container
{
    public $instance = [];

    public function __set($name, $value)
    {
        $this->instance[$name] = $value;
    }
}

class adapter
{
    public $name = '我是调度器';
}

$container = new container();
$container->adapter = new adapter();

class autofelix
{
    private $container;

    public function __construct(container $container)
    {
        $this->container = $container;
    }

    public function who($class)
    {
        return $this->container->instance[$class]->name;
    }
}

$autofelix = new autofelix($container);
$who = $autofelix->who('adapter');
var_dump($who); //我是调度器

进一步优化

  • 如果直接使用就是会将控制的容器中的内容都重新初始化一遍
  • 如果加上闭包就是可以等到使用的时候再初始化减少不必要的浪费
php 复制代码
<?php
$container = new container();
$container->adapter = new adapter(); //高阶优化
$container = new container();
$container->adapter = function () {
    return new adapter();
};
相关推荐
码上淘金1 小时前
【Python】Python常用控制结构详解:条件判断、遍历与循环控制
开发语言·python
Brilliant Nemo2 小时前
四、SpringMVC实战:构建高效表述层框架
开发语言·python
皓月盈江3 小时前
Linux电脑本机使用小皮面板集成环境开发调试WEB项目
linux·php·web开发·phpstudy·小皮面板·集成环境·www.xp.cn
格林威3 小时前
Baumer工业相机堡盟工业相机的工业视觉中为什么偏爱“黑白相机”
开发语言·c++·人工智能·数码相机·计算机视觉
橙子199110163 小时前
在 Kotlin 中什么是委托属性,简要说说其使用场景和原理
android·开发语言·kotlin
androidwork3 小时前
Kotlin Android LeakCanary内存泄漏检测实战
android·开发语言·kotlin
学地理的小胖砸4 小时前
【Python 基础语法】
开发语言·python
笨鸭先游4 小时前
Android Studio的jks文件
android·ide·android studio
gys98954 小时前
android studio开发aar插件,并用uniapp开发APP使用这个aar
android·uni-app·android studio
H309195 小时前
vue3+dhtmlx-gantt实现甘特图展示
android·javascript·甘特图