本篇文章為大家展示了怎么在PHP中定義依賴(lài)注入,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
php,一個(gè)嵌套的縮寫(xiě)名稱(chēng),是英文超級(jí)文本預(yù)處理語(yǔ)言(PHP:Hypertext Preprocessor)的縮寫(xiě)。PHP 是一種 HTML 內(nèi)嵌式的語(yǔ)言,PHP與微軟的ASP頗有幾分相似,都是一種在服務(wù)器端執(zhí)行的嵌入HTML文檔的腳本語(yǔ)言,語(yǔ)言的風(fēng)格有類(lèi)似于C語(yǔ)言,現(xiàn)在被很多的網(wǎng)站編程人員廣泛的運(yùn)用。
一個(gè)數(shù)據(jù)庫(kù)連接類(lèi):
class Mysql{ private $host; private $prot; private $username; private $password; private $db_name; // 構(gòu)造方法 public function __construct(){ $this->host = '127.0.0.1'; $this->port = 22; $this->username = 'root'; $this->password = ''; $this->db_name = 'my_db'; } // 連接 public function connect(){ return mysqli_connect($this->host,$this->username,$this->password,$this->db_name,$this->port); } }
使用這個(gè)類(lèi):
$db = new Mysql(); $db->connect();
通常數(shù)據(jù)庫(kù)連接類(lèi)應(yīng)該設(shè)計(jì)為單列,這里先不要搞復(fù)雜了。
依賴(lài)注入
顯然,數(shù)據(jù)庫(kù)的配置是可以更換的部分,因此我們需要先把它拎出來(lái):
class MysqlConfiguration{ private $host; private $prot; private $username; private $password; private $db_name; public function __construct($host,$port,$username,$password,$db_name){ $this->host = $host; $this->port = $port; $this->username = $username; $this->password = $password; $this->db_name = $db_name; } public function getHost(){ return $this->host; } public function getPort(){ return $this->port(); } public function getUsername(){ return $this->username; } public function getPassword(){ return $this->password; } public function getDbName(){ return $this->db_name; } }
然后不可替換的部分這樣:
class Mysql{ private $configuration; public function __construct($config){ $this->configuration = $config; } // 連接 public function connect(){ return mysqli_connect($this->configuration->getHost(),$this->configuration->getUsername(),$this->configuration->getPassword(),$this->configuration->getDbName(),$this->configuration->getPort()); } }
這樣就完成了配置文件和連接邏輯的分離。
使用
$config = new MysqlConfiguration('127.0.0.1','root','password','my_db',22); // $config是注入Mysql的,這就是所謂的依賴(lài)注入 $db = new Mysql($config); $db->connect();
上述內(nèi)容就是怎么在PHP中定義依賴(lài)注入,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。