適配器模式 將一個類的接口轉換為客戶期望的另一個接口,使原本接口不兼容的類能夠協同工作。對象適配器(組合) 優於類適配器(繼承),靈活性更高。
get/set/deletelog()| 角色 | 本例實現 | 職責 |
|---|---|---|
| Target (目標接口) | DatabaseAdapterInterface | 定義統一的 connect/query/close 契約 |
| Adaptee (被適配者) | 具體驅動類(無共同接口) | 擁有不兼容的原生 API |
| Adapter (適配器) | MysqlAdapter、PdoAdapter、PgsqlAdapter | 實現 Target,內部組合 Adaptee,轉發調用 |
| Client (客戶端) | 業務代碼 | 僅依賴 Target 接口,不知具體適配器 |
<?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;
}
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(); }
}
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; }
}
class PgsqlAdapter implements DatabaseAdapterInterface {
private ?\PgSql\Connection $conn = null;
// 實現類似,使用 pg_* 函數或 PDO (pgsql 驅動)
// 此處省略,結構與 MysqliAdapter 一致
}
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');
| 模式 | 意圖 | 關係 |
|---|---|---|
| 適配器 | 接口轉換(不兼容 → 兼容) | 實現 Target,包裝 Adaptee |
| 門面 | 簡化複雜子系統接口 | 組合多個子系統類,提供高層 API |
| 裝飾器 | 動態添加職責 | 實現 Component,包裝 Component,遞歸結構 |
適配器模式是 「系統集成膠水」。通過 DatabaseAdapterInterface 定義統一契約,具體適配器封裝底層差異(MySQLi/PDO/PgSQL),業務代碼零修改即可切換數據庫引擎。現代框架(Laravel DB、Doctrine DBAL、ThinkPHP Db)底層皆採用此模式。掌握適配器,是構建可插拔、可測試、可遷移架構的關鍵一步。