深入講解laravel6.0框架中的IOC和DI原理
阿新 • • 發佈:2020-08-25
官方解釋:
IOC - 控制反轉 DI - 依賴注入
通俗舉例:
小明以前很窮,風餐露宿,居無定所。現在發財了,自己也想擁有屬於自己的房子,這個時候小明想,要不回老家蓋一棟房子,一來可以住,二來可以光宗耀祖,這個時候,小明需要自己去打造一棟房子;後來小明又想,為何不在城市裡直接買套房呢,生活更加豐富多彩也方便。於是,小明就找了房產中介(IOC容器)買了房子(依賴注入),最終小明很快就住上了屬於自己的房子,開心快樂極了。。。
小明 依賴 房子,小明從自己蓋房子(自己“控制”房子)到找中介買房子(讓中介“控制”房子),這就叫做控制反轉,也就是IOC;而房產中介根據小明的需求,直接把房子提供給小明(當然小明付錢了),這就叫做依賴注入
當然,這個房子並不是房產中介建設的,而是開發商建設的,這個開發商就是服務提供者。
三十年後,小明的這套房子格局跟不上時代了,住得不舒服,想改造/重新裝修房子,但是時間成本太高了,於是,小明又找房產中介買了房子,小明又很快住上新房子了。。。這也體現了面向物件中類的單一職責原則。
目的
採用IOC思想和DI設計模式,主要目的是:解耦
開車式:異地戀。就算中間隔著一個距離,但也不影響真心的相愛著。
原生程式碼實現
傳統寫法
<?php
/**
* Create by PhpStorm
* User : Actor
* Date : 2019-11-01
* Time : 22:03
*/
/**
* Class 購房者
*/
class 購房者
{
private $姓名;
public function __construct($姓名)
{
$this->姓名 = $姓名;
}
public function 買房()
{
$新房 = new 商品房('0001', '四室兩廳', '180平方米');
echo '我是'.$this->姓名."\r\n";
echo '我買了'. $新房->獲取戶型(). '的房子了'."\r\n";
echo '我買了'. $新房->獲取面積(). '的房子了'."\r\n";
}
}
/**
* Class 商品房
*/
class 商品房
{
private $房源編號;
private $戶型;
private $面積;
public function __construct($房源編號, $戶型, $面積)
{
$this->房源編號 = $房源編號;
$this->戶型 = $戶型;
$this->面積 = $面積;
}
public function 獲取面積()
{
return $this->面積;
}
public function 獲取戶型()
{
return $this->戶型;
}
}
$大明 = new 購房者('大明');
$大明->買房();
?>
以上程式碼輸出
[actor20:49:55] /projects/phpAdvanced$ php ioc/iocDriveCar.php
我是大明
我買了四室兩廳的房子了
我買了180平方米的房子了
[actor20:56:18] /projects/phpAdvanced$
採用IOC和DI的思想來實現
<?php
/**
* Create by PhpStorm
* User : Actor
* Date : 2019-11-01
* Time : 22:03
*/
/**
* Class 購房者
*/
class 購房者
{
private $姓名;
public function __construct($姓名)
{
$this->姓名 = $姓名;
}
public function 買房(商品房 $新房)
{
echo '我是'.$this->姓名."\r\n";
echo '我買了'. $新房->獲取戶型(). '的房子了'."\r\n";
echo '我買了'. $新房->獲取面積(). '的房子了'."\r\n";
}
}
/**
* Class 商品房
*/
class 商品房
{
private $房源編號;
private $戶型;
private $面積;
public function __construct($房源編號, $戶型, $面積)
{
$this->房源編號 = $房源編號;
$this->戶型 = $戶型;
$this->面積 = $面積;
}
public function 獲取面積()
{
return $this->面積;
}
public function 獲取戶型()
{
return $this->戶型;
}
}
/**
* 房產中介,就是我們講的ioc
* Class 房產中介
*/
class 房產中介
{
private $在售房源 = [];//這個類似於laravel的Container物件中的$bindings
private $認籌房源 = [];//類似於laravel的Container物件中的$resolved
private $公租房 = [];//類似於laravel的Container物件中的$instances
private $網紅房源 = [];//類似於laravel的Container物件中的$aliases / $abstractAliases
private $意向購房群體 = [];
public function 預售登記($戶型, $詳細資訊)
{
$this->在售房源[$戶型] = $詳細資訊;
}
public function 獲取在售房源($戶型)
{
return ($this->在售房源[$戶型])();//因為是閉包,所以,要增加()來執行閉包函式
}
public function 意向登記($意向人, $個人資訊)
{
$this->意向購房群體[$意向人] = $個人資訊;
}
public function 獲取意向人資訊($意向人)
{