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);
},
$initialInput = 5
);
echo $pipeline; // 输出: (5*2+10)/3 = 6.666...
面向对象的管道类
封装管道操作为独立类,支持动态添加处理阶段:
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
);
}
}
// 使用示例
$result = (new Pipeline())
->add(function ($x) { return $x * 2; })
->add(function ($x) { return $x + 1; })
->process(5); // 输出: 11
Laravel 风格的管道实现
参考 Laravel 的管道设计,支持方法链和异常处理:
class LaravelPipeline
{
protected $passable;
protected $pipes = [];
public function send($passable): self
{
$this->passable = $passable;
return $this;
}
public function through(array $pipes): self
{
$this->pipes = $pipes;
return $this;
}
public function then(callable $destination)
{
$pipeline = array_reduce(
array_reverse($this->pipes),
$this->carry(),
function ($passable) use ($destination) {
return $destination($passable);
}
);
return $pipeline($this->passable);
}
protected function carry(): callable
{
return function ($stack, $pipe) {
return function ($passable) use ($stack, $pipe) {
return $pipe($passable, $stack);
};
};
}
}
// 使用示例
$result = (new LaravelPipeline())
->send(10)
->through([
function ($x, $next) { return $next($x + 5); },
function ($x, $next) { return $next($x * 2); }
])
->then(function ($x) { return $x; }); // 输出: 30
中间件模式扩展
适用于 HTTP 中间件场景的变体实现:
interface Middleware
{
public function handle($request, callable $next);
}
class PipelineWithMiddleware
{
private $middlewares = [];
public function pipe(Middleware $middleware): self
{
$this->middlewares[] = $middleware;
return $this;
}
public function run($request)
{
$handler = array_reduce(
array_reverse($this->middlewares),
function ($next, $middleware) {
return function ($request) use ($middleware, $next) {
return $middleware->handle($request, $next);
};
},
function ($request) { return $request; }
);
return $handler($request);
}
}
关键实现要点
- 可组合性:每个处理阶段应为独立的可调用单元
- 类型安全:建议使用接口约束管道阶段(如
Middleware) - 异常处理:可在管道类中添加
try-catch逻辑统一处理错误 - 性能优化:对于大型管道,可考虑生成静态调用栈减少动态调用开销
实际应用中可根据需求选择简单闭包组合或完整的面向对象实现。







