SPL 定義了 6 大核心接口,構成了 PHP 面向對象標準庫的骨架。本文逐一解析 Countable、OuterIterator、RecursiveIterator、SeekableIterator、SplObserver、SplSubject 的契約與實戰用法。
實現後可直接用 count() 函數計算對象「長度」。
<?php
class PaginatedCollection implements Countable {
private $items = [];
private $totalCount = 0;
public function __construct(array $items, int $totalCount) {
$this->items = $items;
$this->totalCount = $totalCount;
}
public function count(): int {
return $this->totalCount; // 返回總數而非當前頁數量
}
public function getItems(): array { return $this->items; }
}
$collection = new PaginatedCollection(['a', 'b'], 100);
echo count($collection); // 100 (而非 2)
?>
包裝另一個迭代器,修改迭代行為。IteratorIterator 是其標準實現。
<?php
class UpperCaseIterator extends IteratorIterator {
public function current(): mixed {
return strtoupper(parent::current());
}
}
$base = new ArrayIterator(['apple', 'banana', 'cherry']);
$upper = new UpperCaseIterator($base);
foreach ($upper as $key => $value) {
echo "$key => $value\n";
}
// 0 => APPLE
// 1 => BANANA
// 2 => CHERRY
?>
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'pass');
$stmt = $pdo->query('SELECT * FROM users LIMIT 10', PDO::FETCH_ASSOC);
// PDOStatement 實現 Traversable,用 IteratorIterator 包裝成 Iterator
$iterator = new IteratorIterator($stmt);
$users = iterator_to_array($iterator); // 一鍵轉數組
print_r($users);
?>
為多層數據結構(樹、目錄、嵌套數組)提供統一遍歷協議。
<?php
class NestedArrayIterator implements RecursiveIterator {
private $data;
private $position = 0;
public function __construct(array $data) { $this->data = $data; }
// Iterator 接口
public function rewind(): void { $this->position = 0; }
public function valid(): bool { return isset($this->data[$this->position]); }
public function current(): mixed { return $this->data[$this->position]; }
public function key(): mixed { return $this->position; }
public function next(): void { $this->position++; }
// RecursiveIterator 額外方法
public function hasChildren(): bool {
return is_array($this->data[$this->position]);
}
public function getChildren(): RecursiveIterator {
return new self($this->data[$this->position]);
}
}
$data = [1, [10, 20], 3, [4, 5]];
$iterator = new NestedArrayIterator($data);
// 配合 RecursiveIteratorIterator 扁平化遍歷
$flat = new RecursiveIteratorIterator($iterator);
foreach ($flat as $key => $value) {
echo "$key => $value\n";
}
// 0 => 1
// 0 => 10
// 1 => 20
// 1 => 3
// 0 => 4
// 1 => 5
?>
支持 seek($position) 跳轉到指定位置。
<?php
class SeekableArrayIterator implements SeekableIterator {
private $data = ['a', 'b', 'c', 'd'];
private $position = 0;
public function seek(int $position): void {
if (!isset($this->data[$position])) {
throw new OutOfBoundsException("Invalid position: $position");
}
$this->position = $position;
}
// Iterator 方法...
public function rewind(): void { $this->position = 0; }
public function current(): mixed { return $this->data[$this->position]; }
public function key(): mixed { return $this->position; }
public function next(): void { $this->position++; }
public function valid(): bool { return isset($this->data[$this->position]); }
}
$it = new SeekableArrayIterator();
echo $it->current(); // a
$it->seek(2);
echo $it->current(); // c
$it->seek(10); // 拋出 OutOfBoundsException
?>
PHP 內置觀察者模式接口,解耦事件觸發與處理邏輯。
<?php
// 被觀察者
interface SplSubject {
public function attach(SplObserver $observer): void;
public function detach(SplObserver $observer): void;
public function notify(): void;
}
// 觀察者
interface SplObserver {
public function update(SplSubject $subject): void;
}
?>
<?php
class EventDispatcher implements SplSubject {
private $observers = [];
private $eventName;
private $eventData;
public function attach(SplObserver $observer): void {
$this->observers[] = $observer;
}
public function detach(SplObserver $observer): void {
$key = array_search($observer, $this->observers, true);
if ($key !== false) unset($this->observers[$key]);
}
public function notify(): void {
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
public function dispatch(string $event, mixed $data = null): void {
$this->eventName = $event;
$this->eventData = $data;
$this->notify();
}
public function getEventName(): string { return $this->eventName; }
public function getEventData(): mixed { return $this->eventData; }
}
// 具體觀察者
class Logger implements SplObserver {
public function update(SplSubject $subject): void {
if ($subject instanceof EventDispatcher) {
error_log("[LOG] Event: {$subject->getEventName()}, Data: " . json_encode($subject->getEventData()));
}
}
}
class EmailNotifier implements SplObserver {
public function update(SplSubject $subject): void {
if ($subject instanceof EventDispatcher && $subject->getEventName() === 'user.registered') {
// 發送歡迎郵件...
echo "發送郵件給: {$subject->getEventData()['email']}\n";
}
}
}
// 使用
$dispatcher = new EventDispatcher();
$dispatcher->attach(new Logger());
$dispatcher->attach(new EmailNotifier());
$dispatcher->dispatch('user.registered', ['email' => 'user@example.com', 'name' => '張三']);
/* 輸出:
發送郵件給: user@example.com
(日誌寫入文件)
*/
?>
Iterator (內置)
├── OuterIterator
├── RecursiveIterator
│ └── RecursiveIteratorIterator (實現類)
└── SeekableIterator
Countable (獨立)
SplSubject / SplObserver (觀察者模式雙接口)
| 需求 | 推薦接口/類 |
|---|---|
| 對象需支持 count() | 實現 Countable |
| 包裝修改現有迭代器 | 繼承 IteratorIterator (實現 OuterIterator) |
| 遍歷樹形/嵌套結構 | 實現 RecursiveIterator + RecursiveIteratorIterator |
| 需要隨機跳轉訪問 | 實現 SeekableIterator |
| 事件驅動/解耦通知 | 實現 SplSubject/SplObserver |