0
点赞
收藏
分享

微信扫一扫

tp5.1 依赖注入的使用

niboac 2022-06-13 阅读 95


依赖注入的概念:

 

tp5.1  依赖注入的使用_实例化

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

上代码:

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

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());

}
}

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


举报

相关推荐

0 条评论