首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 設計模式實戰:適配器模式統一異構數據庫介面

     編輯:PHP 綜合知識

模式意圖

將一個類的介面轉換為客戶期望的另一介面,使原本不兼容的類能夠協同工作。通俗說:統一異構介面為標準 API。

三大角色

角色說明本例對應
Target(目標介面)客戶期望的標準介面IDatabase
Adaptee(被適配者)現有異構實現mysql_*、pg_* 等原生擴展函數
Adapter(適配器)實現 Target,內部委託 AdapteeMysqlAdapter、PostgresqlAdapter

適用場景

  • 數據庫抽象層:MySQL、PostgreSQL、SQLite、SQL Server 統一介面
  • 緩存抽象:Memcached、Redis、APCu、File Cache 統一介面
  • 第三方 SDK 整合:支付網關、物流查詢、簡訊服務商
  • 遺留系統重構:舊介面漸進式遷移至新介面

核心優勢

  • 客戶端零感知: 僅依賴 Target 介面,切換實現零修改
  • 單一職責:適配邏輯封裝在 Adapter,不污染業務代碼
  • 開閉原則: 新增適配器無需修改現有代碼
  • 測試友好: 可注入 Mock Adapter 進行單元測試

標準實現代碼

<?php
// Target:統一標準介面
interface IDatabase {
    public function connect(string $host, string $user, string $pass, string $db);
    public function query(string $sql): array;
    public function close();
}

// Adapter:MySQL 適配器
class MysqlAdapter implements IDatabase {
    private $conn;
    public function connect($host, $user, $pass, $db) {
        $this->conn = mysqli_connect($host, $user, $pass, $db);
        if (!$this->conn) throw new RuntimeException(mysqli_connect_error());
        mysqli_set_charset($this->conn, 'utf8mb4');
    }
    public function query($sql) {
        $res = mysqli_query($this->conn, $sql);
        if (!$res) throw new RuntimeException(mysqli_error($this->conn));
        return mysqli_fetch_all($res, MYSQLI_ASSOC);
    }
    public function close() { mysqli_close($this->conn); }
}

// Adapter:PostgreSQL 適配器
class PostgresqlAdapter implements IDatabase {
    private $conn;
    public function connect($host, $user, $pass, $db) {
        $dsn = "host=$host dbname=$db user=$user password=$pass";
        $this->conn = pg_connect($dsn);
        if (!$this->conn) throw new RuntimeException(pg_last_error());
    }
    public function query($sql) {
        $res = pg_query($this->conn, $sql);
        if (!$res) throw new RuntimeException(pg_last_error());
        return pg_fetch_all($res) ?: [];
    }
    public function close() { pg_close($this->conn); }
}

// 客戶端:僅依賴 IDatabase
function getUserList(IDatabase $db, int $limit = 10): array {
    return $db->query("SELECT * FROM users LIMIT $limit");
}

// 使用:配置驅動切換實現
$driver = $_ENV['DB_DRIVER'] ?? 'mysql';
$adapter = match ($driver) {
    'mysql'     => new MysqlAdapter(),
    'postgresql' => new PostgresqlAdapter(),
    default     => throw new InvalidArgumentException("Unknown driver: $driver"),
};

$adapter->connect('localhost', 'user', 'pass', 'app_db');
$users = getUserList($adapter);
$adapter->close();
print_r($users);

進階變體:雙向適配器 / 物件適配器

  • 類適配器: 繼承 Adaptee + 實現 Target(PHP 單繼承限制較少用)
  • 物件適配器(組合): 持有 Adaptee 實例,委託調用(推薦,靈活解耦)
  • 雙向適配器: 同時實現兩個 Target 介面,雙向轉換

現代 PHP 生態中的最佳實踐

  • 數據庫層:直接使用 Doctrine DBAL 或 PDO(原生適配器模式實現)
  • 緩存層:PSR-16 Simple Cache / Symfony Cache / Laravel Cache 統一介面
  • HTTP 客戶端:PSR-18 HTTP Client / Guzzle / Symfony HttpClient
  • 日誌:PSR-3 LoggerInterface / Monolog

適配器模式是「介面導向程式設計」的經典落地,**不要重複造輪子**——優先採用社區標準介面(PSR 系列),專注業務邏輯創新。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved