PHP 5.5 引入生成器,5.7/7.0 完善協程支援。生成器本質是**可中斷函數**,`yield` 既可產出值,也可接收外部傳入值 (`send()`),形成雙向通訊。
<?php
function xrange(int $start, int $end, int $step = 1): Generator
{
for ($i = $start; $i <= $end; $i += $step) {
yield $i;
}
}
foreach (xrange(1, 5) as $n) {
echo "$n "; // 1 2 3 4 5
}
// 記憶體常數級,不建立百萬元素陣列
?>
<?php
function logger(string $file): Generator
{
$fp = fopen($file, 'a');
while (true) {
$msg = yield; // 接收外部 send() 的值
fwrite($fp, date('c') . " $msg\n");
}
}
$log = logger(__DIR__ . '/app.log');
$log->send('User login');
$log->send('Order created');
// 協程在 yield 處暫停,send() 喚醒並傳值
?>
<?php
class Task
{
public int $id;
public Generator $coroutine;
public mixed $sendValue = null;
public bool $beforeFirstYield = true;
public function __construct(int $id, Generator $coroutine)
{
$this->id = $id;
$this->coroutine = $coroutine;
}
public function run(): mixed
{
if ($this->beforeFirstYield) {
$this->beforeFirstYield = false;
return $this->coroutine->current();
}
$retval = $this->coroutine->send($this->sendValue);
$this->sendValue = null;
return $retval;
}
public function isFinished(): bool
{
return !$this->coroutine->valid();
}
}
class Scheduler
{
private SplQueue $taskQueue;
private int $tid = 0;
public function __construct()
{
$this->taskQueue = new SplQueue();
}
public function newTask(Generator $coroutine): int
{
$task = new Task(++$this->tid, $coroutine);
$this->taskQueue->enqueue($task);
return $task->id;
}
public function run(): void
{
while (!$this->taskQueue->isEmpty()) {
$task = $this->taskQueue->dequeue();
$task->run();
if ($task->isFinished()) {
echo "Task {$task->id} finished\n";
} else {
$this->taskQueue->enqueue($task);
}
}
}
}
// 示範任務
function taskA(): Generator
{
for ($i = 1; $i <= 3; $i++) {
echo "A$i ";
yield;
}
}
function taskB(): Generator
{
for ($i = 1; $i <= 2; $i++) {
echo "B$i ";
yield;
}
}
$scheduler = new Scheduler();
$scheduler->newTask(taskA());
$scheduler->newTask(taskB());
$scheduler->run();
// 輸出: A1 B1 A2 B2 A3
?>
下篇將介紹非阻塞 I/O 整合、Promise/Deferred 模式、實際網路請求協程化與 ReactPHP/Amp 整合。