使用 yield 实现协程时,核心在于通过生成器(Generator)挂起执行并恢复状态。将回调或 Promise 的异步结果重新注入到生成器的 send() 方法中,即可模拟同步代码的线性逻辑,从而替代深层嵌套的回调。

回调与 Promise 的痛点
传统 PHP 异步编程常依赖回调函数处理 I/O 操作,导致代码出现“回调地狱”,难以维护且错误处理分散。引入 Promise 后,虽然通过链式调用改善了结构,但在复杂业务逻辑中,条件判断与循环内的异步操作仍会引发严重的缩进层级问题。

回调模式在每次异步操作后都需要传入匿名函数,使得控制流被切割成多个片段。Promise 解决了部分嵌套问题,但无法直接支持 try-catch 块包裹整个异步流程,也无法在循环内部自然地暂停等待结果。这种非线性的执行模型增加了调试难度,开发者需要时刻关注上下文状态的传递。
基于 yield 的协程调度器
要实现类同步的异步代码,需构建一个调度器来驱动 Generator。调度器负责启动生成器,捕获其返回的 Promise 对象,并在 Promise 完成时将结果发送回生成器,触发下一次迭代。以下是一个完整的单文件示例,展示了如何运行该调度器。

<?php
class Promise {
private $value;
private $onFulfilled;
private $onRejected;
private $resolved = false;
public function __construct(callable $executor) {
$this->onFulfilled = null;
$this->onRejected = null;
$resolve = function($value) {
if ($this->resolved) return;
$this->resolved = true;
$this->value = $value;
if ($this->onFulfilled) $this->onFulfilled($value);
};
$reject = function($error) {
if ($this->resolved) return;
$this->resolved = true;
$this->value = $error;
if ($this->onRejected) $this->onRejected($error);
};
try {
$executor($resolve, $reject);
} catch (\Exception $e) {
$reject($e);
}
}
public function then(callable $onFulfilled, callable $onRejected = null) {
$this->onFulfilled = $onFulfilled;
$this->onRejected = $onRejected;
return $this;
}
}
function simulateRequest($url) {
return new Promise(function($resolve, $reject) use ($url) {
// 模拟异步延迟
usleep(100000);
if (strpos($url, 'error') !== false) {
$reject(new Exception("Request failed for: $url"));
} else {
$resolve(["status" => 200, "data" => "Content from $url"]);
}
});
}
function runCoroutine(\Generator $generator) {
$promise = $generator->current();
if (!$promise instanceof Promise) {
return $generator->getReturn();
}
$promise->then(
function($value) use ($generator) {
try {
$nextPromise = $generator->send($value);
if ($nextPromise instanceof Promise) {
runCoroutine($generator);
}
} catch (\Exception $e) {
$generator->throw($e);
}
},
function($error) use ($generator) {
try {
$generator->throw($error);
} catch (\Exception $e) {
// 异常已在生成器内部处理
}
}
);
}
// 协程函数
function fetchData() {
try {
$res1 = yield simulateRequest('https://api.example.com/data');
echo "Step 1: " . $res1['data'] . "\n";
$res2 = yield simulateRequest('https://api.example.com/extra');
echo "Step 2: " . $res2['data'] . "\n";
return "Success";
} catch (\Exception $e) {
echo "Error caught: " . $e->getMessage() . "\n";
return "Failed";
}
}
$gen = fetchData();
runCoroutine($gen);
运行上述代码将输出 Step 1 和 Step 2 的内容,证明异步操作按顺序执行。若将 URL 改为包含 'error' 的地址,程序将捕获异常并输出 Error caught 信息,展示统一的错误处理流程。
该程序定义了一个简单的 HTTP 请求模拟器和调度器。用户只需编写类似同步的代码,调度器会自动处理底层的异步切换。确保环境支持 PHP 7.0+ 以使用生成器特性。
yield 对异常处理的影响
使用 yield 进行协程调度时,异常处理机制与常规代码不同。如果 Promise 拒绝(Reject),调度器必须将异常抛出到生成器内部,此时生成器内部的 try-catch 才能捕获该异常,这与同步代码的行为一致。
在上一节的程序中,若模拟的请求失败,调度器会调用 $generator->throw($exception)。这允许开发者在生成器内部使用标准的 try-catch 块来统一处理所有异步步骤的错误,无需在每个 Promise 链末尾单独附加 catch 处理器。这种一致性是协程模式相比 Promise 链的最大优势之一,它使得错误边界清晰且易于管理。