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

$pipeline = array_reduce(
[
function ($input) { return $input * 2; },
function ($input) { return $input + 3; },
function ($input) { return $input / 5; }
],
function ($carry, $callback) {
return $callback($carry);
},
10 // 初始值
);
echo $pipeline; // 输出: 5
面向对象实现
创建可扩展的管道类:
class Pipeline
{
private $stages = [];
public function addStage(callable $stage): self
{
$this->stages[] = $stage;
return $this;
}
public function process($payload)
{
foreach ($this->stages as $stage) {
$payload = $stage($payload);
}
return $payload;
}
}
// 使用示例
$pipeline = (new Pipeline())
->addStage(fn($x) => $x * 2)
->addStage(fn($x) => $x + 3)
->addStage(fn($x) => $x / 5);
echo $pipeline->process(10); // 输出: 5
Laravel 的管道实现
Laravel 框架内置了 Illuminate\Pipeline\Pipeline 类:

use Illuminate\Pipeline\Pipeline;
$result = (new Pipeline(app()))
->send(10)
->through([
function ($input, $next) { return $next($input * 2); },
function ($input, $next) { return $next($input + 3); },
function ($input, $next) { return $next($input / 5); }
])
->thenReturn();
echo $result; // 输出: 5
中间件式管道
适合处理带上下文的请求:
interface Middleware
{
public function handle($request, callable $next);
}
class Pipeline
{
private $middlewares;
public function __construct(array $middlewares)
{
$this->middlewares = $middlewares;
}
public function process($request)
{
$handler = array_reduce(
array_reverse($this->middlewares),
function ($next, $middleware) {
return function ($request) use ($next, $middleware) {
return $middleware->handle($request, $next);
};
},
fn($request) => $request
);
return $handler($request);
}
}
生成器管道
适用于大数据流处理:
function generatorPipeline(array $stages)
{
return function ($data) use ($stages) {
foreach ($stages as $stage) {
$data = $stage($data);
}
yield from $data;
};
}
$pipe = generatorPipeline([
fn($data) => array_map(fn($x) => $x * 2, $data),
fn($data) => array_filter($data, fn($x) => $x > 5)
]);
foreach ($pipe([1, 2, 3, 4, 5]) as $item) {
echo $item . "\n"; // 输出: 6, 8, 10
}
每种实现方式适用于不同场景,闭包方式适合简单转换,面向对象方案更易扩展,Laravel 的方案适合框架集成,生成器方式则适合流式大数据处理。






