欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP經(jīng)典設(shè)計模式之依賴注入定義與用法詳解

 更新時間:2019年05月21日 08:38:21   作者:學(xué)習(xí)筆記666  
這篇文章主要介紹了PHP經(jīng)典設(shè)計模式之依賴注入,結(jié)合實例形式分析了php依賴注入的定義、原理與用法,需要的朋友可以參考下

本文實例講述了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)文章

最新評論