控制反转
简单的一段代码如下:
<?php
class Person {
public function eat() {
$restaurant = new Mcdonald();
echo "I am eating at ".$restaurant->getName()."\n";
}
}
class Mcdonald {
public function getName() {
return "McDonald";
}
}
$person = new Person();
$person->eat();
如果我也会在 Kentucky 吃饭,或者在PizzaHut吃饭,那么我们或许可以写成下面的形式:
<?php
class Person {
private $restaurant;
public function __construct ($restaurant) {
$this->restaurant = $restaurant;
}
public function eat() {
echo "I am eating at ".$this->restaurant->getName()."\n";
}
}
interface Restaurant {
public function getName();
}
class Mcdonald implements Restaurant {
public function getName() {
return "McDonald";
}
}
class Kentucky implements Restaurant {
public function getName() {
return "Kentucky";
}
}
$person = new Person(new Kentucky());
$person->eat();
$person = new Person(new Mcdonald());
$person->eat();
通过构造函数传递restaurant的依赖,这个过程就是依赖注入。
我们添加wear函数。
<?php
class Person {
private $restaurant;
private $shoe;
public function __construct ($restaurant, $shoe) {
$this->restaurant = $restaurant;
$this->shoe = $shoe;
}
public function eat() {
echo "I am eating at ".$this->restaurant->getName()."\n";
}
public function wear() {
echo "I am wearing ".$this->shoe->getName()."\n";
}
}
interface Restaurant {
public function getName();
}
class Mcdonald implements Restaurant {
public function getName() {
return "McDonald";
}
}
class Kentucky implements Restaurant {
public function getName() {
return "Kentucky";
}
}
interface Shoe {
public function getName();
}
class Nike implements Shoe {
public function getName() {
return "Nike";
}
}
class Addidas implements Shoe {
public function getName() {
return "Addidas";
}
}
$restaurant = new Kentucky();
$shoe = new Addidas();
$person = new Person($restaurant, $shoe);
$person->eat();
$person->wear();
在使用的过程中,我们一次注入了$restaurant和$shoe。
Kentucky