作者: | 来源:互联网 | 2023-09-09 06:29
参考:概念:https:blog.csdn.netqq_36172443articledetails82667427应用:http:www.cnblogs.comfinalandd
参考:
概念: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());
}
}
这里的名称和使用区分大小写,请注意!!!