本文實例講述了PHP經典設計模式之依賴注入定義與用法。分享給大家供大家參考,具體如下:
依賴注入的實質就是把一個類不可能更換的部分和可更換的部分分離開來,通過注入的方式來使用,從而達到解耦的目的。
一個數據庫連接類:
class Mysql{ private $host; private $prot; private $username; private $password; private $db_name; // 構造方法 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();
通常數據庫連接類應該設計為單列,這里先不要搞復雜了。
依賴注入
顯然,數據庫的配置是可以更換的部分,因此我們需要先把它拎出來:
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();
希望本文所述對大家PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選