適配器模式將一個類的接口轉換為客戶期望的另一個接口,解決接口不兼容問題。本文以數據庫操作、緩存驅動、支付網關為例,展示 PHP 適配器模式的實戰應用。
| 角色 | 說明 | 代碼映射 |
|---|---|---|
| Target (目標接口) | 客戶期望的統一接口 | interface IDatabase |
| Adaptee (被適配者) | 現有的、不兼容的接口 | mysql_*、pg_* 函數 |
| Adapter (適配器) | 轉換接口的包裝類 | class Mysql/Postgresql |
<?php
// 1. 目標接口:統一的數據庫操作 API
interface IDatabase {
public function connect(string $host, string $username, string $password, string $database): bool;
public function query(string $sql): array;
public function close(): void;
}
// 2. MySQL 適配器
class MysqlAdapter implements IDatabase {
private $connection;
public function connect(string $host, string $username, string $password, string $database): bool {
$this->connection = mysqli_connect($host, $username, $password, $database);
if (!$this->connection) {
throw new Exception("MySQL 連接失敗: " . mysqli_connect_error());
}
mysqli_set_charset($this->connection, 'utf8mb4');
return true;
}
public function query(string $sql): array {
$result = mysqli_query($this->connection, $sql);
if (!$result) {
throw new Exception("查詢失敗: " . mysqli_error($this->connection));
}
$data = [];
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
mysqli_free_result($result);
return $data;
}
public function close(): void {
if ($this->connection) mysqli_close($this->connection);
}
}
// 3. PostgreSQL 適配器
class PostgresqlAdapter implements IDatabase {
private $connection;
public function connect(string $host, string $username, string $password, string $database): bool {
$connStr = "host=$host dbname=$database user=$username password=$password";
$this->connection = pg_connect($connStr);
if (!$this->connection) {
throw new Exception("PostgreSQL 連接失敗: " . pg_last_error());
}
return true;
}
public function query(string $sql): array {
$result = pg_query($this->connection, $sql);
if (!$result) {
throw new Exception("查詢失敗: " . pg_last_error($this->connection));
}
$data = [];
while ($row = pg_fetch_assoc($result)) {
$data[] = $row;
}
pg_free_result($result);
return $data;
}
public function close(): void {
if ($this->connection) pg_close($this->connection);
}
}
// 4. 客戶端代碼:完全面向接口編程
class UserRepository {
private $db;
public function __construct(IDatabase $db) {
$this->db = $db;
}
public function findAll(): array {
$this->db->connect('localhost', 'user', 'pass', 'my_db');
$users = $this->db->query('SELECT * FROM users');
$this->db->close();
return $users;
}
}
// 使用:切換數據庫零修改業務代碼
$db = new PostgresqlAdapter(); // 或 new MysqlAdapter()
$repo = new UserRepository($db);
$users = $repo->findAll();
?>
<?php
interface ICache {
public function get(string $key);
public function set(string $key, $value, int $ttl = 3600): bool;
public function delete(string $key): bool;
}
class RedisCache implements ICache {
private $redis;
public function __construct() {
$this->redis = new Redis();
$this->redis->connect('127.0.0.1', 6379);
}
public function get(string $key) { return $this->redis->get($key); }
public function set(string $key, $value, int $ttl = 3600): bool {
return $this->redis->setex($key, $ttl, json_encode($value));
}
public function delete(string $key): bool { return $this->redis->del($key); }
}
class MemcachedCache implements ICache {
private $memcached;
public function __construct() {
$this->memcached = new Memcached();
$this->memcached->addServer('127.0.0.1', 11211);
}
public function get(string $key) { return $this->memcached->get($key); }
public function set(string $key, $value, int $ttl = 3600): bool {
return $this->memcached->set($key, $value, $ttl);
}
public function delete(string $key): bool { return $this->memcached->delete($key); }
}
// 配置驅動切換
$cacheType = env('CACHE_DRIVER', 'redis'); // redis/memcached
$cache = $cacheType === 'redis' ? new RedisCache() : new MemcachedCache();
?>
<?php
interface IPaymentGateway {
public function pay(float $amount, string $orderNo): array; // 返回 ['success'=>bool, 'trade_no'=>string, 'msg'=>string]
public function refund(string $tradeNo, float $amount): array;
public function verifyNotify(array $data): bool;
}
class AlipayGateway implements IPaymentGateway { /* ... */ }
class WechatGateway implements IPaymentGateway { /* ... */ }
class UnionPayGateway implements IPaymentGateway { /* ... */ }
// 工廠模式創建適配器
class PaymentGatewayFactory {
public static function create(string $type): IPaymentGateway {
return match($type) {
'alipay' => new AlipayGateway(),
'wechat' => new WechatGateway(),
'unionpay' => new UnionPayGateway(),
default => throw new InvalidArgumentException("不支持的支付方式: $type")
};
}
}
// 業務代碼完全解耦
$gateway = PaymentGatewayFactory::create(config('payment.default'));
$result = $gateway->pay(99.00, 'ORDER_20240115001');
?>
當出現以下特徵時考慮適配器模式: