您的位置:首页 > 编程语言 > PHP开发

thinkphp5.1学习过程四——容器与依赖注入的原理

2019-11-20 18:05 1991 查看
**
*容器与依赖注入的原理
*1.任何的URL访问,最终都是定位到控制器,由控制器中某个具体的方动法去执行
*2.一个控制器对应着一个类,如果这些类需要进行统一管理,怎么办?
*容器来进行类管理,还可以将类的实例(对象)做为参数,传递给类方法,自动触发
*依赖注入:将对象类型的数据,以参数的方式传到方法的参数列表
*URL访问:通过GET方式将数据传到控制器指定的方法中,但是只能传字符串,数值
*如果要传一个对象到当前方法中?怎么办?
*依赖注入:解决了向类中的方法传对象的问题
*/
class Demo1
{
//可以通过字符串,数据GET方式来传值到类方法中
public function getName($name='peter')
{
return 'hello '.$name;
}
/**
*\app\common\Temp $temp,将会触发依赖注入
*/
public function getMethod(\app\index\common\Temp $temp)
{
/** \app\common\Temp $temp等价于
*$temp =new \app\index\common\Temp;
*/

$temp->setName('php');
var_dump($temp->getName());
}
//绑定一个类到容器
public function bindClass(){
//把一个类放到容器中:相当于注册到容器中
//\think\Container::set('temp','\app\index\common\Temp');

//将容器中的类实例化并取出来用:实例化时同调用构造器进行初始化
//$temp=\think\Container::get('temp',['name'=>'大海']);

bind('temp','\app\index\common\Temp');
$temp=app('temp',['name'=>'大海之']);
return $temp->getName();
}
//闭包绑定到容器
public function bindClosure(){
\think\Container::set('temp',function($name){
return '欢迎你:'.$name;
});
return \think\Container::get('temp',['name'=>'大海']);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ThinkPHP