本篇文章為大家展示了怎么在PHP中定義依賴注入,內(nèi)容簡明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
php,一個(gè)嵌套的縮寫名稱,是英文超級(jí)文本預(yù)處理語言(PHP:Hypertext Preprocessor)的縮寫。PHP 是一種 HTML 內(nèi)嵌式的語言,PHP與微軟的ASP頗有幾分相似,都是一種在服務(wù)器端執(zhí)行的嵌入HTML文檔的腳本語言,語言的風(fēng)格有類似于C語言,現(xiàn)在被很多的網(wǎng)站編程人員廣泛的運(yùn)用。
一個(gè)數(shù)據(jù)庫連接類:
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è)類:
$db = new Mysql(); $db->connect();
通常數(shù)據(jù)庫連接類應(yīng)該設(shè)計(jì)為單列,這里先不要搞復(fù)雜了。
依賴注入
顯然,數(shù)據(jù)庫的配置是可以更換的部分,因此我們需要先把它拎出來:
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的,這就是所謂的依賴注入 $db = new Mysql($config); $db->connect();
上述內(nèi)容就是怎么在PHP中定義依賴注入,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)頁名稱:怎么在PHP中定義依賴注入-創(chuàng)新互聯(lián)
分享鏈接:http://jinyejixie.com/article2/dighic.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導(dǎo)航、App設(shè)計(jì)、品牌網(wǎng)站建設(shè)、網(wǎng)站收錄、外貿(mào)建站、自適應(yīng)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容