概念:
在ThinkPHP6中,可以使用依赖注入容器来管理和自动解析类之间的依赖关系。将类绑定到容器中,是将一个类和一个回调函数绑定在一起,该回调函数返回一个类实例。在容器中注册一个类之后,可以通过依赖注入容器来获取该类的实例。常见的绑定方式有以下几种:
- 实例绑定:将一个类的实例绑定到容器中。
- 类绑定:将一个类绑定到容器中,每次获取实例时都会创建一个新的实例。
- 单例绑定:将一个类绑定到容器中,每次获取实例时都返回同一个实例。
- 接口绑定:将一个接口与实现该接口的类绑定在一起。
- 上下文绑定:在某些情况下,需要将一个类与特定的上下文(如请求或用户)绑定在一起。
通过将类绑定到容器中,可以使依赖注入更加方便和灵活。
<?php
namespace app\index\controller;
class Demo1
{
//绑定一个类到容器
public function bindClass()
{
//把一个类放到容器中:相当与注册到容器中
\think\Container::set('temp','\app\common\Temp');
//使用助手函数 bind 建议不要使用助手函数
// bind('temp','\app\common\Temp');
//将容器中的类实例化并取出来用:实例化同时调用构造器进行初始化
$temp = \think\Container::get('temp',['name'=>'hyd']);
//使用助手函数 app
// $temp = app('temp',['name'=>'PHP最好的语言']);
return $temp->getName();
}
}
<?php
namespace app\common;
class Temp
{
public function __construct($name="Wyt")
{
$this->name = $name;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return '方法是:'.__METHOD__.'属性是:'.$this->name;
}
}