PHP經(jīng)典設(shè)計模式之依賴注入定義與用法詳解
本文實例講述了PHP經(jīng)典設(shè)計模式之依賴注入定義與用法。分享給大家供大家參考,具體如下:
依賴注入的實質(zhì)就是把一個類不可能更換的部分和可更換的部分分離開來,通過注入的方式來使用,從而達(dá)到解耦的目的。
一個數(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); } }
使用這個類:
$db = new Mysql(); $db->connect();
通常數(shù)據(jù)庫連接類應(yīng)該設(shè)計為單列,這里先不要搞復(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();
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
解決php使用異步調(diào)用獲取數(shù)據(jù)時出現(xiàn)(錯誤c00ce56e導(dǎo)致此項操作無法完成)
本篇文章是對php中使用異步調(diào)用獲取數(shù)據(jù)時出現(xiàn)(由于出現(xiàn)錯誤c00ce56e而導(dǎo)致此項操作無法完成)的解決方法進行了詳細(xì)的分析介紹,需要的朋友參考下2013-07-07PHP實現(xiàn)限制IP訪問及提交次數(shù)的方法詳解
這篇文章主要介紹了PHP實現(xiàn)限制IP訪問及提交次數(shù)的方法,涉及php針對客戶端來訪IP的獲取、判斷以及結(jié)合session記錄IP訪問次數(shù)等相關(guān)操作技巧,需要的朋友可以參考下2017-07-07round robin權(quán)重輪循算法php實現(xiàn)代碼
這篇文章主要介紹了round robin權(quán)重輪循算法php實現(xiàn)代碼,需要的朋友可以參考下2016-05-05php恢復(fù)數(shù)組的key為數(shù)字序列的方法
這篇文章主要介紹了php恢復(fù)數(shù)組的key為數(shù)字序列的方法,涉及php操作數(shù)組鍵名的技巧,需要的朋友可以參考下2015-04-04php 過濾英文標(biāo)點符號及過濾中文標(biāo)點符號代碼
這篇文章主要介紹了php過濾英文標(biāo)點符號及過濾中文標(biāo)點符號的方法,需要的朋友可以參考下2014-06-06php+mysqli事務(wù)控制實現(xiàn)銀行轉(zhuǎn)賬實例
這篇文章主要介紹了php+mysqli事務(wù)控制實現(xiàn)銀行轉(zhuǎn)賬,實例分析了事物控制的原理與事物回滾的使用技巧,需要的朋友可以參考下2015-01-01