介面定義了類別必須實作的「契約」,規範公開方法簽名,不關心具體實作。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
| 特性 | 介面 | 抽象類別 |
|---|---|---|
| 多重實作 | ✅ 可實作多個 | ❌ 單繼承 |
| 狀態 (屬性) | PHP 8.1+ readonly 常數/屬性 | ✅ 完整支援 |
| 建構子 | ❌ 無 | ✅ 可強制簽名 |
| 預設實作 | PHP 8.0+ default 方法 | ✅ 完整支援 |
| 用途 | 定義「能做什麼」 (能力) | 定義「是什麼」 (基礎骨架) |
<?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
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; }
}
?>
<?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;
}
?>
xxxInterface / xxxContract:傳統 Laravel 風格xxxable:能力導向 (如 Serializable, Countable, Loggable)xxxRepository / xxxService:領域驅動設計$app->bind(Interface::class, Impl::class)<?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 原則 拆分介面、面向介面編程、依賴注入容器管理實作,能構建高內聚、低耦合、易測試、易擴充的系統架構。