php管道实现
PHP 管道模式实现
管道模式(Pipeline Pattern)是一种将任务分解为多个步骤的设计模式,每个步骤由独立的处理器完成,数据通过管道依次传递。以下是 PHP 中实现管道模式的几种方法:
使用闭包和数组迭代
通过闭包和 array_reduce 实现管道:

$pipeline = array_reduce(
[
function ($input) { return $input * 2; },
function ($input) { return $input + 10; },
function ($input) { return $input / 3; }
],
function ($carry, $callback) {
return $callback($carry);
},
5 // 初始输入值
);
echo $pipeline; // 输出: 6.6666666666667
面向对象的管道类
封装管道逻辑为可复用的类:

class Pipeline
{
private $stages = [];
public function add(callable $stage): self
{
$this->stages[] = $stage;
return $this;
}
public function process($payload)
{
return array_reduce(
$this->stages,
function ($carry, $stage) {
return $stage($carry);
},
$payload
);
}
}
// 使用示例
$pipeline = (new Pipeline)
->add(function ($x) { return $x * 2; })
->add(function ($x) { return $x + 10; })
->add(function ($x) { return $x / 3; });
echo $pipeline->process(5); // 输出相同结果
中间件风格的管道
适用于请求-响应场景的变体:
interface Middleware
{
public function handle($request, callable $next);
}
class Pipeline
{
private $stages = [];
public function pipe(Middleware $middleware): self
{
$this->stages[] = $middleware;
return $this;
}
public function run($request)
{
$runner = array_reduce(
array_reverse($this->stages),
function ($next, $stage) {
return function ($request) use ($next, $stage) {
return $stage->handle($request, $next);
};
},
function ($request) { return $request; }
);
return $runner($request);
}
}
Laravel 风格的管道
参考 Laravel 框架的实现方式:
function pipeline($passable, array $pipes)
{
return array_reduce(
array_reverse($pipes),
function ($carry, $pipe) {
return $pipe($carry);
},
$passable
);
}
关键注意事项
- 不可变数据:每个管道阶段应返回新值而非修改原输入
- 类型安全:确保阶段之间的输入输出类型兼容
- 错误处理:可添加 try-catch 或专门的错误处理阶段
- 性能考量:大量阶段时考虑生成器或流式处理
以上实现可根据具体需求选择,面向对象方式更适合复杂业务逻辑,闭包方式适合简单数据处理。






