萬盛學電腦網

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

PHP 多重介面實作深度解析:組合複雜行為與介面隔離原則

為什麼需要多重介面?

PHP 單繼承限制了類別只能有一個父類,但現實領域模型常需組合多種能力:可識別、可命名、可序列化、可記錄日誌、可快取... 多重介面實作正是解決此問題的標準方案,實現「組合大於繼承」。

核心範例:員工實體組合多重介面

<?php
declare(strict_types=1);

// 核心識別介面
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;
}

// 序列化介面
interface SerializableEntity
{
    public function toArray(): array;
    public static function fromArray(array $data): self;
}

// 軟刪除介面
interface SoftDeletable
{
    public function isDeleted(): bool;
    public function delete(): void;
    public function restore(): void;
}

// 實作多重介面
class Staff implements 
    Identifiable, 
    Nameable, 
    Timestampable, 
    SerializableEntity,
    SoftDeletable
{
    private int $id;
    private string $name;
    private DateTimeImmutable $createdAt;
    private DateTimeImmutable $updatedAt;
    private bool $deleted = false;
    
    public function __construct()
    {
        $now = new DateTimeImmutable();
        $this->createdAt = $now;
        $this->updatedAt = $now;
    }
    
    // Identifiable
    public function getId(): int { return $this->id; }
    public function setId(int $id): void { 
        if ($id <= 0) throw new InvalidArgumentException('ID must be positive');
        $this->id = $id; 
    }
    
    // Nameable
    public function getName(): string { return $this->name; }
    public function setName(string $name): void { 
        $this->name = trim($name);
        $this->updatedAt = new DateTimeImmutable();
    }
    
    // Timestampable
    public function getCreatedAt(): DateTimeImmutable { return $this->createdAt; }
    public function getUpdatedAt(): DateTimeImmutable { return $this->updatedAt; }
    
    // SerializableEntity
    public function toArray(): array
    {
        return [
            'id'         => $this->id,
            'name'       => $this->name,
            'created_at' => $this->createdAt->format('c'),
            'updated_at' => $this->updatedAt->format('c'),
            'deleted'    => $this->deleted,
        ];
    }
    
    public static function fromArray(array $data): self
    {
        $staff = new self();
        $staff->setId($data['id']);
        $staff->setName($data['name']);
        $staff->createdAt = new DateTimeImmutable($data['created_at']);
        $staff->updatedAt = new DateTimeImmutable($data['updated_at']);
        $staff->deleted = $data['deleted'] ?? false;
        return $staff;
    }
    
    // SoftDeletable
    public function isDeleted(): bool { return $this->deleted; }
    public function delete(): void { 
        $this->deleted = true; 
        $this->updatedAt = new DateTimeImmutable();
    }
    public function restore(): void { 
        $this->deleted = false; 
        $this->updatedAt = new DateTimeImmutable();
    }
    
    // 額外業務方法
    public function getDisplayName(): string
    {
        return $this->deleted ? "[已刪除] {$this->name}" : $this->name;
    }
}
?>

介面型別提示與多型運用

<?php
// 依賴具體介面而非具體類別
function persistEntity(SerializableEntity $entity): void
{
    $data = $entity->toArray();
    // 儲存至資料庫、Redis、檔案...
    echo "儲存: " . json_encode($data, JSON_UNESCAPED_UNICODE) . "\n";
}

function logEntity(Timestampable $entity): void
{
    echo "建立時間: {$entity->getCreatedAt()->format('Y-m-d H:i:s')}\n";
    echo "更新時間: {$entity->getUpdatedAt()->format('Y-m-d H:i:s')}\n";
}

function softDelete(SoftDeletable $entity): void
{
    if (!$entity->isDeleted()) {
        $entity->delete();
        echo "軟刪除完成\n";
    }
}

// 同一物件可滿足多種介面需求
$staff = new Staff();
$staff->setId(101);
$staff->setName('張三');

persistEntity($staff); // 接受 SerializableEntity
logEntity($staff);     // 接受 Timestampable
softDelete($staff);    // 接受 SoftDeletable

// 型別檢查
var_dump($staff instanceof Identifiable);      // true
var_dump($staff instanceof Nameable);          // true
var_dump($staff instanceof Timestampable);     // true
var_dump($staff instanceof SerializableEntity); // true
var_dump($staff instanceof SoftDeletable);     // true
var_dump($staff instanceof Countable);         // false (未實作)
?>

介面隔離原則 (ISP) 實戰

將龐大介面拆分為專職小介面,類別只實作所需能力:

<?php
// ❌ 違反 ISP:強迫所有使用者實作不需要的方法
interface FatUserInterface
{
    public function getId(): int;
    public function getEmail(): string;
    public function sendNotification(string $msg): void;  // 一般用戶不需要
    public function generateApiToken(): string;           // 一般用戶不需要
    public function getAdminPanelUrl(): string;           // 只有管理員需要
    public function assignPermission(string $perm): void; // 只有管理員需要
}

// ✅ 遵循 ISP:拆分為最小介面
interface UserIdentity
{
    public function getId(): int;
    public function getEmail(): string;
}

interface Notifiable
{
    public function sendNotification(string $message): void;
}

interface ApiAccessible
{
    public function generateApiToken(): string;
}

interface AdminAccessible
{
    public function getAdminPanelUrl(): string;
    public function assignPermission(string $permission): void;
}

// 一般用戶只實作核心介面
class RegularUser implements UserIdentity
{
    public function __construct(
        private int $id,
        private string $email
    ) {}
    public function getId(): int { return $this->id; }
    public function getEmail(): string { return $this->email; }
}

// 管理員組合多介面
class AdminUser implements UserIdentity, Notifiable, ApiAccessible, AdminAccessible
{
    // 實作所有方法...
}

// 服務層依賴最小介面
function notifyUser(Notifiable $user, string $msg): void
{
    $user->sendNotification($msg);
}

// 只有實作 Notifiable 的物件能傳入
// notifyUser(new RegularUser(1, 'a@b.com'), 'hi'); // ❌ 型別錯誤
notifyUser(new AdminUser(...), 'hi'); // ✅ 正確
?>

介面衝突解決:同名方法不同簽名

<?php
interface A
{
    public function process(string $data): string;
}

interface B
{
    public function process(int $data): int; // 簽名衝突!
}

// PHP 8.1+ 支援聯集型別解決
interface C
{
    public function process(string|int $data): string|int;
}

class Resolver implements A, B
{
    // 必須相容兩個介面簽名
    // PHP 8.0+ 允許回傳型別聯集,參數型別需相容 (逆變)
    public function process(string|int $data): string|int
    {
        if (is_string($data)) return strtoupper($data);
        return $data * 2;
    }
}
?>

Trait 輔助介面實作 (避免重複代碼)

<?php
trait IdentifiableTrait
{
    private int $id = 0;
    public function getId(): int { return $this->id; }
    public function setId(int $id): void { $this->id = $id; }
}

trait NameableTrait
{
    private string $name = '';
    public function getName(): string { return $this->name; }
    public function setName(string $name): void { $this->name = $name; }
}

trait TimestampableTrait
{
    private DateTimeImmutable $createdAt;
    private DateTimeImmutable $updatedAt;
    
    public function __construct()
    {
        $this->createdAt = new DateTimeImmutable();
        $this->updatedAt = $this->createdAt;
    }
    
    public function getCreatedAt(): DateTimeImmutable { return $this->createdAt; }
    public function getUpdatedAt(): DateTimeImmutable { return $this->updatedAt; }
    
    protected function touch(): void { $this->updatedAt = new DateTimeImmutable(); }
}

// 組合使用
class Product implements Identifiable, Nameable, Timestampable
{
    use IdentifiableTrait, NameableTrait, TimestampableTrait;
    
    // 只需實作業務邏輯,基礎能力由 Trait 提供
    private float $price = 0;
    
    public function setPrice(float $price): void 
    { 
        $this->price = $price; 
        $this->touch(); // 更新時間戳
    }
}
?>

介面契約測試策略

<?php
// 介面契約測試:確保所有實作類別符合規範
abstract class IdentifiableContractTest extends TestCase
{
    abstract protected function createInstance(): Identifiable;
    
    public function testIdMustBePositiveInteger(): void
    {
        $entity = $this->createInstance();
        $entity->setId(42);
        $this->assertEquals(42, $entity->getId());
    }
    
    public function testIdRejectsZero(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $entity = $this->createInstance();
        $entity->setId(0);
    }
    
    public function testIdRejectsNegative(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $entity = $this->createInstance();
        $entity->setId(-1);
    }
}

// 針對每個實作類別執行契約測試
class StaffIdentifiableTest extends IdentifiableContractTest
{
    protected function createInstance(): Identifiable
    {
        return new Staff();
    }
}

class ProductIdentifiableTest extends IdentifiableContractTest
{
    protected function createInstance(): Identifiable
    {
        return new Product();
    }
}
?>

總結

多重介面實作是 PHP 實現「組合大於繼承」的核心機制。關鍵原則:

  1. 介面要小、要專:遵循 ISP,每個介面只定義單一能力
  2. 面向介面編程:函數參數、返回型別、容器綁定都用介面
  3. Trait 復用實作:將通用邏輯提取到 Trait,類別組合多個 Trait
  4. 契約測試:為介面編寫抽象測試,所有實作自動驗證
  5. PHP 8+ 善用新特性:default 方法、readonly 屬性、聯集型別

掌握多重介面設計,能構建出高度模組化、可替換、易測試的領域模型。

copyright © 萬盛學電腦網 all rights reserved