前言
第一部分: 半协程调度器
- 统一生成器接口
- 生成器迭代
- 生成器返回值
- 生成器委托
- 改写 return
- 抽象异步模型
- 引入异常处理
- 异常: 嵌套任务透传
- 异常: 传递流程
- 异常: 重新进行 CPS 变换
- 异常: 重新加入 Async
- Syscall 与 Context
- 调度器: 里程碑
- spawn
- callcc
- race 与 timeout
- all 与 parallel
- channel 与协程间通信
- 无缓存 channel
- 缓存 channel
- channel 演示
- FutureTask 与 fork
第二部分: Koa
- 穿越地心之旅
- 洋葱圈模型
- rightReduce与中间件compose
- Koa::Application
- Koa::Context
- Koa::Request
- Koa::Response
- Koa - HelloWorld
- Middleware Interface
- Middleware: 全局异常处理
- Middleware: Router
- Middleware: 请求超时
- 一个综合示例
附录
参考
文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
rightReduce与中间件compose
rightReduce与中间件compose
然后,有心同学可能会发现,我们的makeTravel其实是一个对函数列表进行rightReduce的函数:
<?php
function compose(...$fns)
{
return array_right_reduce($fns, function($carry, $fn) {
return function() use($carry, $fn) {
$fn($carry);
};
});
}
function array_right_reduce(array $input, callable $function, $initial = null)
{
return array_reduce(array_reverse($input, true), $function, $initial);
}
将上述makeTravel替换成compose,我们将得到完全相同的结果。
我们修改函数列表中函数的签名,middleware :: (Context $ctx, Generator $next) -> void
,我们把满足List<Middleware>
的函数列表进行组合(rightReduce),得到中间件入口函数,只需要稍加改造,我们的compose方法便可以处理生成器函数,用来支持我们上文的半协程:
<?php
function compose(...$middleware)
{
return function(Context $ctx = null) use($middleware) {
$ctx = $ctx ?: new Context(); // Context 参见下文
$next = null;
$i = count($middleware);
while ($i--) {
$curr = $middleware[$i];
$next = $curr($ctx, $next);
assert($next instanceof \Generator);
}
return $next;
};
}
如果是中间件是\Closure,打包过程可以可以将$this变量绑定到$ctx,中间件内可以使用$this代替$ctx,Koa1.x采用这种方式, Koa2.x已经废弃;
if ($middleware[$i] instanceof \Closure) {
//
$curr = $middleware[$i]->bindTo($ctx, Context::class);
}
rightReduce版本:
<?php
function compose(array $middleware)
{
return function(Context $ctx = null) use($middleware) {
$ctx = $ctx ?: new Context(); // Context 参见下文
return array_right_reduce($middleware, function($rightNext, $leftFn) use($ctx) {
return $leftFn($ctx, $rightNext);
}, null);
};
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论