php設計模式-依賴注入的使用詳解

黄舟
發布: 2023-03-14 09:54:02
原創
1370 人瀏覽過

前言 

 終於要講到這個著名的設計原則,其實它比其他設計模式都簡單。
 依賴注入的實質就是把一個類別不可能更換的部分 和 可更換的部分 分離開來,透過注入的方式來使用,從而達到解耦的目的。

這裡就舉個資料庫連結的栗子,希望大家理解

一個資料庫連接類別

class Mysql{
    private $host;
    private $port;
    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();
$con = $db->connect();
登入後複製

通常應該設計為單例,這裡就先不搞複雜了。

依賴注入

顯然,資料庫的配置是可以更換的部分,因此我們需要把它拎出來。

class MysqlConfiguration
{
    private $host;
    private $port;
    private $username;
    private $password;
    private $db_name;
    public function construct(string $host, int $port, string $username, string $password,string $db_name)
    {
        $this->host = $host;
        $this->port = $port;
        $this->username = $username;
        $this->password = $password;
        $this->db_name = $db_name;
    }
    public function getHost(): string
    {
        return $this->host;
    }
    public function getPort(): int
    {
        return $this->port;
    }
    public function getUsername(): string
    {
        return $this->username;
    }
    public function getPassword(): string
    {
        return $this->password;
    }
    public function getDbName(): string
    {
        return $this->db_name;
    }
}
登入後複製

然後不可替換的部分這樣:

class Mysql
{
    private $configuration;
    public function construct(DatabaseConfiguration $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','','my_db',22);
$db = new Mysql($config);
$con = $db->connect();
登入後複製

$config是注入Mysql的,這就是所謂的依賴注入。

以上是php設計模式-依賴注入的使用詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!