tp5.1 依赖注入的使用

参考:
概念:https://blog.csdn.net/qq_36172443/article/details/82667427
应用: http://www.cnblogs.com/finalanddistance/p/8960669.html

依赖注入的概念:

 

分享图片

总结一点就是 底层类应该依赖于上层类,避免上层类依赖于底层类。

代码

首先先写几个需要用到的控制器;

demo3:

<?PHP
namespace app\index\controller;

class Demo3
{
    private $content = ‘我是demo3!!!‘;

    public function text()
    {
        return  $this -> content;
    }

    public function setText($string)
    {
        $this -> content = $string;
    }

    public function getName()
    {
        $name = ‘我是demo3的名字‘;
        return $name;
    }
}

demo2:

<?PHP
namespace app\index\controller;

class Demo2
{
    private $Demo3;
    public function __construct(Demo3 $demo)
    {
       $this -> Demo3 = $demo;
    }

    public function text()
    {
        return $this -> Demo3 -> text();
    }

    public function getName()
    {
        return $this -> Demo3 -> getName();
    }
}

demo1:

<?PHP
namespace app\index\controller;

class Demo1
{
    private $Demo2;
    public function __construct(Demo2 $demo2)
    {
       $this -> Demo2 = $demo2;
    }

    public function text()
    {
        return $this -> Demo2 -> text();
    }

    public function getName()
    {
        return $this -> Demo2 -> getName();
    }
}

然后是我们的使用方法

一般的使用的方法是:

<?PHP
namespace app\index\controller;

class Demo
{
   public function index()
   {
       $demo3 = new \app\index\controller\Demo3();
       $demo2 = new \app\index\controller\Demo2($demo3);
       $demo1 = new \app\index\controller\Demo1($demo2);
       dump($demo1 -> text());
       dump($demo1 -> getName());
   }
}

你看,是不是很麻烦,一个类依赖另外一个类,一个一个的实例化,麻烦的很,但是你用tp5.1里面的方法就不用理会这些了,tp框架自动帮你实例化!

tp5.1的使用方法

<?PHP
namespace app\index\controller;

class Demo
{
   public function index()
   {
       \think\Container::set(‘demo1‘,‘\app\index\controller\Demo1‘);
       $demo1 =  \think\Container::get(‘demo1‘);
       dump($demo1 -> text());
       dump($demo1 -> getName());

   }
}

这里的名称和使用区分大小写,请注意!!!

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...