roquie/pipeline

即插即用型管道实现。

0.1.1 2015-09-29 10:27 UTC

This package is auto-updated.

Last update: 2024-09-24 04:11:03 UTC


README

Software License Packagist Version Total Downloads Minimum PHP Version

此包提供了管道模式实现。

管道模式

管道模式允许您通过链式连接阶段来轻松组合顺序阶段。

在本特定实现中,接口由两部分组成

  • StageInterface
  • PipelineInterface

管道由零个、一个或多个阶段组成。管道可以处理有效载荷。在处理过程中,有效载荷将被传递到第一个阶段。从那时起,结果值将从阶段传递到阶段。

在最简单的情况下,执行链可以表示为foreach

$result = $payload;

foreach ($stages as $stage) {
    $result = $stage->process($result);
}

return $result;

不可变性

管道被实现为不可变的阶段链。当您通过管道添加新阶段时,将创建一个新的管道,其中包含添加的阶段。这使得管道易于重用,并最小化了副作用。

简单示例

use Roquie\Pipeline\Pipeline;
use Roquie\Pipeline\StageInterface;

class TimesTwoStage implements StageInterface
{
    public function process($payload)
    {
        return $payload * 2;
    }
}

class AddOneStage implements StageInterface
{
    public function process($payload)
    {
        return $payload + 1;
    }
}

$pipeline = (new Pipeline)
    ->pipe(new TimesTwoStage)
    ->pipe(new AddOneStage);

// Returns 21
$pipeline->process(10);

可重用管道

由于PipelineInterface是StageInterface的扩展,因此管道可以作为阶段重用。这创建了一个高度可组合的模型,用于创建复杂的执行模式,同时保持认知负载较低。

例如,如果我们想组合一个处理API调用的管道,我们将创建类似以下内容

$processApiRequest = (new Pipeline)
    ->pipe(new ExecuteHttpRequest) // 2
    ->pipe(new ParseJsonResponse); // 3
    
$pipeline = (new Pipeline)
    ->pipe(new ConvertToPsr7Request) // 1
    ->pipe($processApiRequest) // (2,3)
    ->pipe(new ConvertToResponseDto); // 4 
    
$pipeline->process(new DeleteBlogPost($postId));

可调用阶段

CallableStage类被提供以封装满足callable类型提示的参数。此类使您能够将任何类型的可调用作为阶段使用。

$pipeline = (new Pipeline)
    ->pipe(CallableStage::forCallable(function ($payload) {
        return $payload * 10;
    }));

// or

$pipeline = (new Pipeline)
    ->pipe(new CallableStage(function ($payload) {
        return $payload * 10;
    }));

管道构建器

由于管道本身是不可变的,因此引入了管道构建器以简化管道的分布式组合。

管道构建器收集阶段,并允许您在任何给定时间创建管道。

use Roquie\Pipeline\PipelineBuilder;

// Prepare the builder
$pipelineBuilder = (new PipelineBuilder)
    ->add(new LogicalStage)
    ->add(new AnotherStage)
    ->add(new LastStage);

// Build the pipeline
$pipeline = $pipelineBuilder->build();

异常处理

在此包中处理异常时完全透明。此包不会捕获任何异常或沉默错误。异常应根据具体情况处理。要么在阶段内部,要么在管道处理有效载荷时。

$pipeline = (new Pipeline)
    ->pipe(CallableStage::forCallable(function () {
        throw new LogicException();
    });
    
try {
    $pipeline->process($payload);
} catch(LogicException $e) {
    // Handle the exception.
}