依赖注入

依赖注入(DI)指的就是当你需要实例化的类依赖于其他类的实现的时候;

不需要在本类中实例化所依赖的类,而是将所依赖的类通过参数的形式传入 即构造注入(构造函数)和设值注入(set方法);

高耦合的反例

//高耦合

class Apple
{
​ protected $name = ‘ ‘;

public function construct()
{
$this- >name = ‘Apple ‘;
}

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

class Orange
{
​ protected $name = ‘ ‘;

public function
construct()
{
$this- >name = ‘Orange ‘;
}

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

class Person
{
​ protected $likeFood = ‘ ‘;

public function construct()
{
$this- >likeFood = new Orange();
echo ‘这个人喜欢吃 ‘ . $this- >likeFood- >getName();
}
}

new Person();

低耦合注入

//低耦合实现
interface Fruit
{
​ public function getName();

}

class Apple implements Fruit
{
​ protected $name = ‘ ‘;

public function construct()
{
$this- >name = ‘Apple ‘;
}

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

class Orange implements Fruit
{
​ protected $name = ‘ ‘;

public function construct()
{
$this- >name = ‘Orange ‘;
}

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

class Person
{
​ public $likeFood;

public function
construct(Fruit $fruit)
{
echo ‘这个人喜欢吃 ‘ . $fruit- >getName();
}
}

$apple = new Apple();
new Person($apple);