国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

PHP經典設計模式之依賴注入定義與用法詳解

2024-05-05 00:09:07
字體:
來源:轉載
供稿:網友

本文實例講述了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程序設計有所幫助。


注:相關教程知識閱讀請移步到PHP教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 惠来县| 蒙自县| 南澳县| 泰州市| 东海县| 沙田区| 阿克陶县| 赣榆县| 巴楚县| 台南市| 吴江市| 西藏| 湖北省| 黄平县| 曲水县| 汨罗市| 中方县| 濮阳市| 台湾省| 从化市| 唐海县| 桂平市| 安平县| 宣威市| 壶关县| 浙江省| 株洲市| 诏安县| 惠水县| 富平县| 龙州县| 霍山县| 安丘市| 神木县| 玉山县| 遂昌县| 固始县| 田林县| 马山县| 方城县| 凤阳县|