萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 設計模式:適配器模式實戰——統一 MySQL、PostgreSQL、PDO 多數據庫訪問接口

模式定義

適配器模式 將一個類的接口轉換為客戶期望的另一個接口,使原本接口不兼容的類能夠協同工作。對象適配器(組合) 優於類適配器(繼承),靈活性更高。

適用場景

  • 整合第三方庫、舊系統、API 接口不統一
  • 數據庫抽象層:MySQLi、PDO、PostgreSQL、SQL Server 統一調用
  • 緩存適配器:Redis、Memcached、File、APCu 統一 get/set/delete
  • 日誌適配器:Monolog、File、Syslog、Slack 統一 log()

角色結構

角色本例實現職責
Target (目標接口)DatabaseAdapterInterface定義統一的 connect/query/close 契約
Adaptee (被適配者)具體驅動類(無共同接口)擁有不兼容的原生 API
Adapter (適配器)MysqlAdapter、PdoAdapter、PgsqlAdapter實現 Target,內部組合 Adaptee,轉發調用
Client (客戶端)業務代碼僅依賴 Target 接口,不知具體適配器

完整代碼實現

1. 統一目標接口

<?php
interface DatabaseAdapterInterface {
    public function connect(array $config): bool;
    public function query(string $sql, array $params = []): iterable|false;
    public function execute(string $sql, array $params = []): int;
    public function lastInsertId(): string|false;
    public function beginTransaction(): bool;
    public function commit(): bool;
    public function rollBack(): bool;
    public function close(): void;
}

2. 具體適配器:MySQLi 版

class MysqliAdapter implements DatabaseAdapterInterface {
    private ?mysqli $conn = null;

    public function connect(array $config): bool {
        $this->conn = new mysqli(
            $config['host'] ?? '127.0.0.1',
            $config['user'] ?? 'root',
            $config['pass'] ?? '',
            $config['dbname'] ?? 'test',
            $config['port'] ?? 3306
        );
        if ($this->conn->connect_errno) {
            throw new Exception("MySQLi 連接失敗: {$this->conn->connect_error}");
        }
        $this->conn->set_charset($config['charset'] ?? 'utf8mb4');
        return true;
    }

    public function query(string $sql, array $params = []): iterable|false {
        if ($params) {
            $stmt = $this->conn->prepare($sql);
            $types = str_repeat('s', count($params)); // 簡化:全部按字符串綁定
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $result = $stmt->get_result();
            return $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
        }
        return $this->conn->query($sql)?->fetch_all(MYSQLI_ASSOC) ?? false;
    }

    public function execute(string $sql, array $params = []): int {
        if ($params) {
            $stmt = $this->conn->prepare($sql);
            $types = str_repeat('s', count($params));
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            return $stmt->affected_rows;
        }
        $this->conn->query($sql);
        return $this->conn->affected_rows;
    }

    public function lastInsertId(): string|false {
        return $this->conn->insert_id ?: false;
    }

    public function beginTransaction(): bool { return $this->conn->begin_transaction(); }
    public function commit(): bool { return $this->conn->commit(); }
    public function rollBack(): bool { return $this->conn->rollback(); }
    public function close(): void { if ($this->conn) $this->conn->close(); }
}

3. 具體適配器:PDO 版(推薦生產使用)

class PdoAdapter implements DatabaseAdapterInterface {
    private ?PDO $pdo = null;

    public function connect(array $config): bool {
        $dsn = "mysql:host={$config['host']};dbname={$config['dbname']};charset={$config['charset'] ?? 'utf8mb4'}";
        $this->pdo = new PDO($dsn, $config['user'], $config['pass'], [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ]);
        return true;
    }

    public function query(string $sql, array $params = []): iterable|false {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    }

    public function execute(string $sql, array $params = []): int {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->rowCount();
    }

    public function lastInsertId(): string|false { return $this->pdo->lastInsertId(); }
    public function beginTransaction(): bool { return $this->pdo->beginTransaction(); }
    public function commit(): bool { return $this->pdo->commit(); }
    public function rollBack(): bool { return $this->pdo->rollBack(); }
    public function close(): void { $this->pdo = null; }
}

4. 具體適配器:PostgreSQL 版

class PgsqlAdapter implements DatabaseAdapterInterface {
    private ?\PgSql\Connection $conn = null;
    // 實現類似,使用 pg_* 函數或 PDO (pgsql 驅動)
    // 此處省略,結構與 MysqliAdapter 一致
}

5. 工廠創建適配器(可選)

class DatabaseAdapterFactory {
    public static function create(string $driver, array $config): DatabaseAdapterInterface {
        return match ($driver) {
            'mysqli' => new MysqliAdapter(),
            'pdo'    => new PdoAdapter(),
            'pgsql'  => new PgsqlAdapter(),
            default  => throw new InvalidArgumentException("Unsupported driver: {$driver}"),
        };
    }
}

客戶端使用:零感知切換

<?php
// 配置文件 config/db.php
return [
    'driver' => 'pdo', // 或 'mysqli'
    'host'   => '127.0.0.1',
    'user'   => 'app',
    'pass'   => 'secret',
    'dbname' => 'myapp',
];

// 业务代码
$config = require 'config/db.php';
$db = DatabaseAdapterFactory::create($config['driver'], $config);
$db->connect($config);

$users = $db->query("SELECT * FROM users WHERE status = ?", ['active']);
foreach ($users as $user) {
    echo "{$user['username']} 
"; } $db->execute("UPDATE users SET last_login = NOW() WHERE id = ?", [1]); $db->close();

進階:緩存適配器統一接口

interface CacheAdapterInterface {
    public function get(string $key): mixed;
    public function set(string $key, mixed $value, int $ttl = 3600): bool;
    public function delete(string $key): bool;
    public function clear(): bool;
}

class RedisCacheAdapter implements CacheAdapterInterface { /* 實現 Redis 操作 */ }
class FileCacheAdapter implements CacheAdapterInterface { /* 實現文件緩存 */ }
class ArrayCacheAdapter implements CacheAdapterInterface { /* 內存陣列,測試用 */ }

// 使用
$cache = new RedisCacheAdapter();
$cache->set('key', 'value', 600);
$val = $cache->get('key');

適配器 vs 門面 vs 裝飾器

模式意圖關係
適配器接口轉換(不兼容 → 兼容)實現 Target,包裝 Adaptee
門面簡化複雜子系統接口組合多個子系統類,提供高層 API
裝飾器動態添加職責實現 Component,包裝 Component,遞歸結構

總結

適配器模式是 「系統集成膠水」。通過 DatabaseAdapterInterface 定義統一契約,具體適配器封裝底層差異(MySQLi/PDO/PgSQL),業務代碼零修改即可切換數據庫引擎。現代框架(Laravel DB、Doctrine DBAL、ThinkPHP Db)底層皆採用此模式。掌握適配器,是構建可插拔、可測試、可遷移架構的關鍵一步。

copyright © 萬盛學電腦網 all rights reserved