溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么在PHP中定義依賴注入

發(fā)布時(shí)間:2021-05-10 17:22:03 來源:億速云 閱讀:120 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章為大家展示了怎么在PHP中定義依賴注入,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

php是什么語言

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)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI