萬盛學電腦網

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

PHP 設計模式實戰:適配器模式統一異構接口(數據庫/緩存/支付)

適配器模式:讓不兼容的接口協同工作

適配器模式將一個類的接口轉換為客戶期望的另一個接口,解決接口不兼容問題。本文以數據庫操作、緩存驅動、支付網關為例,展示 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');
?>

優勢總結

  • 解耦:業務邏輯依賴抽象接口,不依賴具體實現
  • 可擴展:新增適配器無需修改現有代碼 (OCP 原則)
  • 可測試:易於 Mock 接口進行單元測試
  • 遷移平滑:數據庫遷移、緩存切換、支付增加渠道零業務代碼變更

適用場景判斷

當出現以下特徵時考慮適配器模式:

  1. 需要使用現有類,但其接口不符合需求
  2. 想創建可復用的類,協同不相關的類
  3. 需要統一多個異構系統的調用方式
  4. 第三方庫升級導致接口變化,不想修改業務代碼
copyright © 萬盛學電腦網 all rights reserved