萬盛學電腦網

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

PHP 介面 vs 抽象類:核心差異、適用場景與代碼實戰

一句話總結

介面 定義「能做什麼」 (契約);抽象類 提供「怎麼做」 (部分實現/共享邏輯)。

核心差異對比表

特性介面抽象類
方法實現全部為抽象 (PHP 8.0+ 可有預設實現)可混合抽象與具體方法
屬性僅常數 (public static const)可有任意可見性屬性、常數
建構子不能有可有,子類可呼叫 parent::__construct()
繼承關係implements,可多實現extends,單一繼承
設計意圖規範行為契約、多型、解耦代碼復用、模板方法、共享狀態
關鍵字interfaceabstract class

場景一:介面 — 定義插件/驅動契約

支付網關:系統不關心具體怎麼支付,只關心「必須有 pay/refund/query 方法」。

<?php
interface PaymentGateway {
    public function pay(float $amount, string $orderId): PaymentResult;
    public function refund(string $transactionId, float $amount): RefundResult;
    public function query(string $transactionId): TransactionStatus;
}

// 支付寶實現
class AlipayGateway implements PaymentGateway {
    public function pay(float $amount, string $orderId): PaymentResult { /* ... */ }
    public function refund(string $transactionId, float $amount): RefundResult { /* ... */ }
    public function query(string $transactionId): TransactionStatus { /* ... */ }
}

// 微信支付實現
class WechatGateway implements PaymentGateway { /* ... */ }

// 服務類依賴介面,而非具體實現 (依賴倒置)
class OrderService {
    public function __construct(private PaymentGateway $gateway) {}
    public function checkout(Order $order): void {
        $result = $this->gateway->pay($order->total, $order->id);
        // ...
    }
}

場景二:抽象類 — 模板方法模式 (共享流程骨架)

報表導出:步驟固定 (查詢 → 轉換 → 輸出),但查詢 SQL、轉換格式各異。

<?php
abstract class ReportExporter {
    // 模板方法:定義算法骨架
    final public function export(array $criteria, string $outputPath): void {
        $data = $this->fetchData($criteria);       // 子類實現
        $formatted = $this->format($data);         // 子類實現
        $this->write($formatted, $outputPath);     // 父類提供預設實現
    }

    abstract protected function fetchData(array $criteria): iterable;
    abstract protected function format(iterable $data): string;

    // 共享邏輯:寫入檔案
    protected function write(string $content, string $path): void {
        $dir = dirname($path);
        if (!is_dir($dir)) mkdir($dir, 0755, true);
        file_put_contents($path, $content);
    }
}

// CSV 導出
class CsvExporter extends ReportExporter {
    protected function fetchData(array $criteria): iterable {
        // 執行 SQL 返回 Generator 節省記憶體
        yield from $this->db->query('SELECT * FROM orders WHERE ...');
    }
    protected function format(iterable $data): string {
        $out = fopen('php://temp', 'r+');
        fputcsv($out, ['ID','Amount','Date']);
        foreach ($data as $row) fputcsv($out, $row);
        rewind($out);
        return stream_get_contents($out);
    }
}

// Excel 導出 (繼承共享 write、只改 format)
class ExcelExporter extends ReportExporter {
    protected function fetchData(array $criteria): iterable { /* ... */ }
    protected function format(iterable $data): string {
        // 使用 PhpSpreadsheet 生成 xlsx
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        // ...
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $stream = fopen('php://temp', 'r+');
        $writer->save($stream);
        rewind($stream);
        return stream_get_contents($stream);
    }
}

場景三:介面 + 抽象類 組合 (最佳實踐)

// 1. 定義契約
interface CacheDriver {
    public function get(string $key): mixed;
    public function set(string $key, mixed $value, int $ttl): bool;
    public function delete(string $key): bool;
}

// 2. 抽象基類提供通用邏輯 (鍵前綴、序列化、事件)
abstract class BaseCacheDriver implements CacheDriver {
    protected string $prefix = '';
    public function __construct(string $prefix = '') { $this->prefix = $prefix; }
    protected function normalizeKey(string $key): string { return $this->prefix . $key; }
    protected function serialize(mixed $value): string { return serialize($value); }
    protected function unserialize(string $data): mixed { return unserialize($data); }
    // 可選:事件觸發、日誌、指標統計...
}

// 3. 具體實現
class RedisCache extends BaseCacheDriver {
    public function __construct(\Redis $redis, string $prefix = '') {
        parent::__construct($prefix);
        $this->redis = $redis;
    }
    public function get(string $key): mixed {
        $data = $this->redis->get($this->normalizeKey($key));
        return $data ? $this->unserialize($data) : null;
    }
    public function set(string $key, mixed $value, int $ttl): bool {
        return $this->redis->setex($this->normalizeKey($key), $ttl, $this->serialize($value));
    }
    public function delete(string $key): bool {
        return (bool)$this->redis->del($this->normalizeKey($key));
    }
}

class FileCache extends BaseCacheDriver { /* ... */ }

決策流程圖

需要定義「行為契約」給多方實現? → 是 → 使用 interface
需要共享「代碼/狀態/流程骨架」給子類? → 是 → 使用 abstract class
兩者都需要? → 定義 interface,再提供 abstract class 實現該 interface 作為基類

PHP 8.0+ 新特性:介面預設實現

interface Loggable {
    public function log(string $message, string $level = 'info'): void;
    // PHP 8.0+ 允許預設實現
    public function logDebug(string $message): void {
        $this->log($message, 'debug');
    }
}

這模糊了介面/抽象類界線,但**核心設計意圖不變**:介面仍為契約,抽象類仍為復用載體。

copyright © 萬盛學電腦網 all rights reserved