萬盛學電腦網

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

PHP 介面實作完整指南:單一介面、多重介面與契約設計

介面在 PHP 中的角色

介面定義了類別必須實作的「契約」,規範公開方法簽名,不關心具體實作。PHP 介面支援:方法簽名、常數、PHP 8.1+ 的 readonly 屬性、PHP 8.0+ 的聯集型別。善用介面可實現依賴倒置、多型、可測試性、外掛架構。

單一介面實作範例

<?php
declare(strict_types=1);

interface StaffInterface
{
    public function setId(int $id): void;
    public function getId(): int;
    public function setName(string $name): void;
    public function getName(): string;
}

class Staff implements StaffInterface
{
    private int $id;
    private string $name;
    
    public function setId(int $id): void
    {
        if ($id <= 0) throw new InvalidArgumentException('ID 必須為正整數');
        $this->id = $id;
    }
    
    public function getId(): int
    {
        return $this->id;
    }
    
    public function setName(string $name): void
    {
        $this->name = trim($name);
    }
    
    public function getName(): string
    {
        return $this->name;
    }
    
    // 類別可擁有介面未定義的方法
    public function getDisplayName(): string
    {
        return "Staff #{$this->id}: {$this->name}";
    }
}

// 依賴介面而非具體類別
function printStaffInfo(StaffInterface $staff): void
{
    echo $staff->getDisplayName() . "\n";
}

$staff = new Staff();
$staff->setId(145);
$staff->setName('Simon');
printStaffInfo($staff); // Staff #145: Simon
?>

多重介面實作

PHP 單繼承但可實作多個介面,解決「菱形繼承」問題,實現介面隔離原則 (ISP)。

<?php
interface Identifiable
{
    public function getId(): int;
    public function setId(int $id): void;
}

interface Nameable
{
    public function getName(): string;
    public function setName(string $name): void;
}

interface Timestampable
{
    public function getCreatedAt(): DateTimeImmutable;
    public function getUpdatedAt(): DateTimeImmutable;
}

class Staff implements Identifiable, Nameable, Timestampable
{
    private int $id;
    private string $name;
    private DateTimeImmutable $createdAt;
    private DateTimeImmutable $updatedAt;
    
    public function __construct()
    {
        $this->createdAt = new DateTimeImmutable();
        $this->updatedAt = $this->createdAt;
    }
    
    public function getId(): int { return $this->id; }
    public function setId(int $id): void { $this->id = $id; }
    public function getName(): string { return $this->name; }
    public function setName(string $name): void { 
        $this->name = $name;
        $this->updatedAt = new DateTimeImmutable();
    }
    public function getCreatedAt(): DateTimeImmutable { return $this->createdAt; }
    public function getUpdatedAt(): DateTimeImmutable { return $this->updatedAt; }
}

// 介面型別提示
function logActivity(Identifiable $entity): void
{
    error_log("Entity ID: {$entity->getId()}");
}

function sendNotification(Nameable $recipient): void
{
    echo "通知 {$recipient->getName()}\n";
}

$staff = new Staff();
$staff->setId(1);
$staff->setName('Alice');

logActivity($staff);      // 接受 Identifiable
sendNotification($staff); // 接受 Nameable

介面 vs 抽象類別:選擇指南

特性介面抽象類別
多重實作✅ 可實作多個❌ 單繼承
狀態 (屬性)PHP 8.1+ readonly 常數/屬性✅ 完整支援
建構子❌ 無✅ 可強制簽名
預設實作PHP 8.0+ default 方法✅ 完整支援
用途定義「能做什麼」 (能力)定義「是什麼」 (基礎骨架)

PHP 8+ 介面新特性

預設方法實作 (PHP 8.0+)

<?php
interface Loggable
{
    public function getLogContext(): array;
    
    // 預設實作,類別可選擇覆寫
    public function log(string $level, string $message): void
    {
        $context = $this->getLogContext();
        error_log("[$level] $message " . json_encode($context));
    }
}

class User implements Loggable
{
    public function __construct(
        private int $id,
        private string $name
    ) {}
    
    public function getLogContext(): array
    {
        return ['user_id' => $this->id, 'user_name' => $this->name];
    }
    
    // 可選擇覆寫 log() 方法
}
?>

唯讀屬性介面 (PHP 8.1+)

<?php
interface EntityInterface
{
    public readonly int $id; // 介面定義 readonly 屬性
    public function getId(): int;
}

class User implements EntityInterface
{
    public function __construct(
        public readonly int $id,
        public readonly string $name
    ) {}
    
    public function getId(): int { return $this->id; }
}
?>

介面設計最佳實踐

1. 介面隔離原則 (ISP)

<?php
// ❌ 違反 ISP:胖介面
interface UserManager
{
    public function create(array $data): User;
    public function update(int $id, array $data): User;
    public function delete(int $id): bool;
    public function sendEmail(int $id, string $subject): void;
    public function exportPdf(int $id): string;
    public function assignRole(int $id, string $role): void;
}

// ✅ 遵循 ISP:拆分為專職介面
interface UserRepository
{
    public function create(array $data): User;
    public function update(int $id, array $data): User;
    public function delete(int $id): bool;
    public function find(int $id): ?User;
}

interface UserNotifier
{
    public function sendEmail(int $userId, string $subject, string $body): void;
}

interface UserExporter
{
    public function exportPdf(int $userId): string;
}

interface UserAuthorization
{
    public function assignRole(int $userId, string $role): void;
}
?>

2. 介面命名慣例

  • xxxInterface / xxxContract:傳統 Laravel 風格
  • xxxable:能力導向 (如 Serializable, Countable, Loggable)
  • xxxRepository / xxxService:領域驅動設計

3. 介面驅動開發流程

  1. 先定義介面契約
  2. 編寫測試針對介面 (Mock 介面)
  3. 實作具體類別
  4. 綁定容器:$app->bind(Interface::class, Impl::class)
  5. 依賴注入使用介面型別提示

實戰範例:外掛系統架構

<?php
interface PaymentGatewayInterface
{
    public function charge(float $amount, string $currency): PaymentResult;
    public function refund(string $transactionId): RefundResult;
    public function getSupportedCurrencies(): array;
    public function getName(): string;
}

class StripeGateway implements PaymentGatewayInterface
{
    public function charge(float $amount, string $currency): PaymentResult { /* ... */ }
    public function refund(string $transactionId): RefundResult { /* ... */ }
    public function getSupportedCurrencies(): array { return ['USD', 'EUR', 'TWD']; }
    public function getName(): string { return 'Stripe'; }
}

class PaymentService
{
    public function __construct(
        private PaymentGatewayInterface $gateway
    ) {}
    
    public function processOrder(Order $order): PaymentResult
    {
        return $this->gateway->charge($order->total, $order->currency);
    }
}

// 容器綁定 (Laravel 範例)
$app->bind(PaymentGatewayInterface::class, fn() => new StripeGateway());
// 或根據配置動態切換
$app->bind(PaymentGatewayInterface::class, function() {
    return config('payment.gateway') === 'stripe' 
        ? new StripeGateway() 
        : new PayPalGateway();
});
?>

總結

介面是 PHP 物件導向設計的基石。單一介面定義核心契約,多重介面組合複雜行為,PHP 8+ 新特性 (default 方法、readonly 屬性) 進一步強化表達力。遵循 ISP 原則 拆分介面、面向介面編程、依賴注入容器管理實作,能構建高內聚、低耦合、易測試、易擴充的系統架構。

copyright © 萬盛學電腦網 all rights reserved