当前位置:首页 > PHP

php实现pipeline

2026-01-29 09:13:57PHP

PHP 实现 Pipeline 模式

Pipeline(管道)模式是一种将多个处理步骤串联起来的设计模式,每个步骤处理输入并传递给下一个步骤。在 PHP 中可以通过多种方式实现。

基础实现方式

使用闭包和数组包装步骤,通过循环依次调用:

php实现pipeline

$pipeline = [
    function ($input) { return $input * 2; },
    function ($input) { return $input + 10; },
    function ($input) { return $input / 3; }
];

$result = 5;
foreach ($pipeline as $step) {
    $result = $step($result);
}
echo $result; // 输出: 6.666...

面向对象实现

创建 Pipeline 类管理步骤和执行流程:

class Pipeline
{
    private $steps = [];

    public function addStep(callable $step)
    {
        $this->steps[] = $step;
        return $this;
    }

    public function process($input)
    {
        foreach ($this->steps as $step) {
            $input = $step($input);
        }
        return $input;
    }
}

// 使用示例
$pipeline = new Pipeline();
$pipeline->addStep(fn($x) => $x * 2)
         ->addStep(fn($x) => $x + 10)
         ->addStep(fn($x) => $x / 3);

echo $pipeline->process(5); // 输出: 6.666...

中间件风格的实现

适用于请求处理场景,每个步骤可以决定是否中断管道:

php实现pipeline

class MiddlewarePipeline
{
    private $middlewares = [];
    private $index = 0;

    public function addMiddleware(callable $middleware)
    {
        $this->middlewares[] = $middleware;
    }

    public function handle($request)
    {
        if (!isset($this->middlewares[$this->index])) {
            return $request;
        }

        $middleware = $this->middlewares[$this->index];
        $this->index++;

        return $middleware($request, fn($req) => $this->handle($req));
    }
}

// 使用示例
$pipeline = new MiddlewarePipeline();
$pipeline->addMiddleware(function ($req, $next) {
    $req['user'] = 'admin';
    return $next($req);
});
$pipeline->addMiddleware(function ($req, $next) {
    $req['logged'] = true;
    return $next($req);
});

$result = $pipeline->handle([]);
print_r($result); // 输出包含 user 和 logged 的数组

Laravel 风格的 Pipeline

模仿 Laravel 框架的实现方式:

class LaravelPipeline
{
    protected $passable;
    protected $pipes = [];

    public function send($passable)
    {
        $this->passable = $passable;
        return $this;
    }

    public function through(array $pipes)
    {
        $this->pipes = $pipes;
        return $this;
    }

    public function then(callable $destination)
    {
        $pipeline = array_reduce(
            array_reverse($this->pipes),
            $this->carry(),
            fn($passable) => $destination($passable)
        );

        return $pipeline($this->passable);
    }

    protected function carry()
    {
        return function ($stack, $pipe) {
            return function ($passable) use ($stack, $pipe) {
                return $pipe($passable, $stack);
            };
        };
    }
}

// 使用示例
$pipeline = new LaravelPipeline();
$result = $pipeline->send(5)
    ->through([
        function ($passable, $next) { return $next($passable * 2); },
        function ($passable, $next) { return $next($passable + 10); },
        function ($passable, $next) { return $next($passable / 3); }
    ])
    ->then(function ($result) {
        return $result;
    });

echo $result; // 输出: 6.666...

异常处理增强版

为管道添加异常处理能力:

class SafePipeline
{
    private $steps = [];
    private $handlers = [];

    public function addStep(callable $step)
    {
        $this->steps[] = $step;
        return $this;
    }

    public function addHandler(string $exceptionClass, callable $handler)
    {
        $this->handlers[$exceptionClass] = $handler;
        return $this;
    }

    public function process($input)
    {
        try {
            foreach ($this->steps as $step) {
                $input = $step($input);
            }
            return $input;
        } catch (Throwable $e) {
            foreach ($this->handlers as $exceptionClass => $handler) {
                if ($e instanceof $exceptionClass) {
                    return $handler($e, $input);
                }
            }
            throw $e;
        }
    }
}

// 使用示例
$pipeline = new SafePipeline();
$pipeline->addStep(fn($x) => $x * 2)
         ->addStep(function ($x) {
             if ($x > 100) throw new RuntimeException('Value too large');
             return $x + 10;
         })
         ->addHandler(RuntimeException::class, fn($e, $x) => $x / 2);

echo $pipeline->process(50); // 输出: 55 (50*2=100, +10=110 → 触发异常 → 110/2=55)

这些实现方式展示了 PHP 中 Pipeline 模式的不同应用场景和变体,可以根据具体需求选择合适的实现方案。

标签: phppipeline
分享给朋友:

相关文章

php实现文件下载

php实现文件下载

PHP 实现文件下载的方法 使用 header() 函数强制下载 设置正确的 HTTP 头信息,强制浏览器下载文件而不是直接打开。 $file = 'path/to/file.pdf'; if (f…

php实现上传

php实现上传

PHP 文件上传实现 HTML 表单设置 创建一个包含文件上传字段的 HTML 表单,确保表单的 enctype 属性设置为 multipart/form-data,这是文件上传必需的设置。 <…

php验证码实现

php验证码实现

验证码实现方法 在PHP中实现验证码功能通常涉及生成随机字符串或数字,将其转换为图像,并通过会话(Session)进行验证。以下是几种常见的实现方式: 使用GD库生成图像验证码 GD库是PHP内置的…

php实现静态

php实现静态

静态化实现方法 PHP实现静态化主要通过生成HTML文件或缓存机制来减少服务器动态解析的开销。以下是几种常见方法: 生成静态HTML文件 通过file_put_contents()将动态内容保存为H…

php实现推送

php实现推送

PHP 实现推送功能的方法 PHP 实现推送功能可以通过多种方式完成,包括 WebSocket、Server-Sent Events (SSE)、长轮询或第三方推送服务。以下是几种常见的方法: 使用…

php数组实现

php数组实现

PHP 数组的基本实现 PHP 数组是一种非常灵活的数据结构,可以存储多个值,并且支持多种类型的键(整数或字符串)。PHP 数组实际上是有序映射(ordered map),可以看作是列表(vector…