print "enter your name"read nameprint "enter your address"read addressetc...store in database
从而控制用户交互的流程。
在GUI程序或其他程序中,我们会说:
when the user types in field a, store it in NAMEwhen the user types in field b, store it in ADDRESSwhen the user clicks the save button, call StoreInDatabase
public class MeetingMember {
private GlassOfWater glassOfWater;
...
public void setGlassOfWater(GlassOfWater glassOfWater){this.glassOfWater = glassOfWater;}//your glassOfWater object initialized and ready to use...//spring IoC called setGlassOfWater method itself in order to//offer to meetingMember glassOfWater instance
}
控制反转(Inversion of Control,或IoC)是关于获得自由(你结婚了,你失去了自由,你被控制了。你离婚了,你刚刚实施了控制反转。这就是我们所说的“解耦”。良好的计算机系统不鼓励一些非常亲密的关系。)更大的灵活性(你办公室的厨房只供应干净的自来水,这是你想喝的唯一选择。你的老板通过安装一台新咖啡机来实施控制反转。现在你可以灵活地选择自来水或咖啡。)和减少依赖(你的伴侣有工作,你没有工作,你在经济上依赖你的伴侣,所以你被控制了。你找到了一份工作,你已经实施了控制反转。良好的计算机系统鼓励依赖性。)
class SomeController{private $storage;
function __construct(StorageServiceInterface $storage){$this->storage = $storage;}
public function myFunction (){return $this->storage->getFile($fileName);}}
class GoogleDriveService implements StorageServiceInterface{public function authenticate($user) {}public function putFile($file) {}public function getFile($file) {}}
class SomeController{private $storage;
function __construct(){$this->storage = new GoogleDriveService();}
public function myFunction (){return $this->storage->getFile($fileName);}}
function isVarHello($var) {return ($var === "Hello");}
// Responsibility is within the caller$word = "Hello";if (isVarHello($word)) {$word = "World";}
现在让我们通过将结果的责任从调用者转移到依赖项来反转控制:
function changeHelloToWorld(&$var) {// Responsibility has been shifted to the dependencyif ($var === "Hello") {$var = "World";}}
$word = "Hello";changeHelloToWorld($word);
下面是另一个使用OOP的例子:
<?php
class Human {private $hp = 0.5;
function consume(Eatable $chunk) {// $this->chew($chunk);$chunk->unfoldEffectOn($this);}
function incrementHealth() {$this->hp++;}function isHealthy() {}function getHungry() {}// ...}
interface Eatable {public function unfoldEffectOn($body);}
class Medicine implements Eatable {function unfoldEffectOn($human) {// The dependency is now in charge of the human.$human->incrementHealth();$this->depleted = true;}}
$human = new Human();$medicine = new Medicine();if (!$human->isHealthy()) {$human->consume($medicine);}
var_dump($medicine);var_dump($human);