fiberphp / pipeline
🔗 FiberPHP 洋葱模型管道构造器 —— 零依赖的中间件管线核心。
v0.1.0
2026-11-22 11:09 UTC
Requires
- php: >=8.5
- ext-posix: *
Requires (Dev)
- phpstan/phpstan: ^2.0
- phpunit/phpunit: ^11.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-22 11:11:04 UTC
README
零依赖的洋葱模型管道构造器,把中间件列表编译为可缓存的闭包,供请求处理链复用。
环境要求
- PHP >= 8.5
- 无扩展与第三方包依赖
安装
composer require fiberphp/pipeline
快速上手
use Closure;
use FiberPHP\Pipeline\Pipeline;
$pipeline = Pipeline::build(
[
static function (mixed $request, Closure $next): mixed {
$request['started_at'] = microtime(true);
return $next($request);
},
static function (mixed $request, Closure $next): mixed {
$response = $next($request);
return $response . ' (checked)';
},
],
static fn (mixed $request): string => 'ok',
);
echo $pipeline(['path' => '/users']); // ok (checked)
Pipeline::build() 只构造闭包,不创建 Fiber;在已有协程或普通同步流程中都可直接调用。
参数签名
| 参数 | 类型 | 说明 |
|---|---|---|
$pipes | array<int, callable> | 管道列表,签名 ($passable, Closure $next): mixed,按数组顺序从外到内执行 |
$destination | Closure | 终点闭包,签名 ($passable): mixed |
$catch | ?Closure | 异常处理闭包,签名 (Throwable $e, $passable): mixed;省略时异常向上抛出 |
返回值为闭包,签名 ($passable): mixed,可直接保存复用。
执行顺序
管道按声明顺序进入、逆序返回,形成洋葱模型:
use Closure;
use FiberPHP\Pipeline\Pipeline;
$log = [];
$pipeline = Pipeline::build(
[
static function (mixed $value, Closure $next) use (&$log): mixed {
$log[] = 'A-before';
$result = $next($value);
$log[] = 'A-after';
return $result;
},
static function (mixed $value, Closure $next) use (&$log): mixed {
$log[] = 'B-before';
$result = $next($value);
$log[] = 'B-after';
return $result;
},
],
static fn (mixed $value): string => 'done',
);
$pipeline('payload'); // ['A-before', 'B-before', 'B-after', 'A-after']
管道不调用 $next 即可短路,后续管道与终点都不会执行:
$pipes = [
// 直接返回,不调用 $next
static fn (mixed $request, Closure $next): string => 'blocked',
];
异常处理
传入 $catch 后,任一管道或终点抛出的异常都会交给它处理,返回值即为管道结果;无管道时终点同样受保护:
use FiberPHP\Pipeline\Pipeline;
use RuntimeException;
use Throwable;
$pipeline = Pipeline::build(
[
static function (mixed $request, Closure $next): mixed {
throw new RuntimeException('boom');
},
],
static fn (mixed $request): string => 'ok',
static fn (Throwable $e, mixed $request): string => 'caught: ' . $e->getMessage(),
);
echo $pipeline('payload'); // caught: boom
未传 $catch 时异常原样向上抛出。
测试
composer test
与其它包的关系
fiberphp/http的请求中间件基于本包build()编译。- 编译结果是闭包,可在常驻 Worker 内缓存复用。
- 零依赖,其它需要洋葱模型的场景可独立使用。
License
MIT