当前位置:首页 > 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实现分页的基本方法 使用原生PHP实现分页功能需要结合数据库查询和HTML展示。以下是核心实现步骤: 数据库查询与分页逻辑 // 连接数据库 $conn = new mysqli('lo…

php实现搜索功能

php实现搜索功能

实现基础搜索功能 使用PHP和MySQL实现基础的搜索功能需要结合表单提交与数据库查询。创建一个HTML表单用于接收用户输入的搜索关键词,通过PHP处理表单数据并查询数据库。 // 搜索表单 (HT…

php实现图片上传

php实现图片上传

实现图片上传的基本步骤 创建HTML表单用于文件上传,表单需设置enctype="multipart/form-data"属性,确保文件数据正确传输。 <form action="upload…

php 实现自动收货

php 实现自动收货

PHP 实现自动收货功能 自动收货功能通常用于电商系统,在订单超过一定时间未手动确认收货时自动完成订单。以下是实现方法: 数据库设计 需要订单表包含以下关键字段: CREATE TABLE…

php实现socket

php实现socket

PHP 实现 Socket 通信 PHP 可以通过 socket 扩展实现网络通信,支持 TCP/UDP 协议。以下是实现 Socket 通信的核心步骤和代码示例。 创建 TCP 服务器 // 创建…

php实现增删改查

php实现增删改查

以下是在PHP中实现增删改查(CRUD)操作的详细方法,以MySQL数据库为例: 数据库连接配置 创建config.php文件存储数据库连接信息: <?php $host = 'loca…