solidworx/piper

PHP 管道工作流程

dev-master 2017-01-26 14:34 UTC

This package is not auto-updated.

Last update: 2024-09-15 00:40:05 UTC


README

Build Status

Piper 是一个 PHP 管道流程库。它允许你将多个流程按顺序执行。

目录

要求

Piper 需要 PHP 7.1+

安装

Composer

$ composer require solidworx/piper:^2.0

使用方法

基本使用

想象你有一个电子商务网站,用户可以在网上购买商品。当用户下单时,会有几件事情需要发生,例如:下单、向用户发送订单确认邮件、向网站管理员发送订单通知、创建发货标签等。

所有这些流程可以连接起来,按顺序执行。

<?php

use SolidWorx\Piper\Piper;
use SolidWorx\Piper\PipeInterface;
use SolidWorx\Piper\Context;

class PlaceOrder implements PipeInterface
{
    public function process(Context $context)
    {
        // Place the order in the database
    }
}

$piper = new Piper();

$piper->pipe(new PlaceOrder())
    ->pipe(new SendEmailConfirmation())
    ->pipe(new SendOrderPlacedEmail())
    ->pipe(new CreateShippingLabel())
    ;

$piper->process();

这将从调用 PlaceOrder 类的 process 方法开始,然后是 SendEmailConfirmation 等。该 process 方法将处理所有在继续到下一步之前需要的逻辑。

在进程间传递信息

有时你需要在步骤之间传递信息,例如,第一步可能是下单,然后在发送确认邮件时需要订单 ID。

在这种情况下,你可以使用 Context 类来设置信息。该对象在步骤之间传递,你可以添加或获取信息。

<?php

use SolidWorx\Piper\PipeInterface;
use SolidWorx\Piper\Context;

class PlaceOrder implements PipeInterface
{
    public function process(Context $context)
    {
        $orderId = // Place the order in the database and get the id
        
        $context->set('orderId', $orderId);
    }
}

class SendEmailConfirmation implements PipeInterface
{
    public function process(Context $context)
    {
        // Get the order id from the previous step
        $orderId = $context->get('orderId');
    }
}

使用初始数据启动进程

如果你想在管道流程中用一组初始数据(例如用户 ID)开始,则只需传递一个 Context 类的实例。

<?php

use SolidWorx\Piper\Context;
use SolidWorx\Piper\Piper;

$context = new Context(['userId' => 123]);

$piper->process($context);

回滚更改

如果你想回滚步骤所做的更改,则可以在你的步骤中实现 RollbackInterface

每当任何步骤发生错误时,都会扫描所有前面的步骤以检查可能的回滚。如果步骤实现了 RollbackInterface 接口,则将执行 rollback 方法,在该步骤中可以撤销所做的任何更改。

<?php

use SolidWorx\Piper\RollbackInterface;
use SolidWorx\Piper\Context;

class PlaceOrder implements RollbackInterface
{
    public function process(Context $context)
    {
    }
    
    public function rollback(Context $context)
    {
        // An error occurred during the checkout process, undo the order here
    }
}

使用可调用对象

管道步骤也可以接受任何可调用对象。当步骤没有太多逻辑且不需要独立类时,这很有用。

<?php

use SolidWorx\Piper\Context;
use SolidWorx\Piper\Piper;

$piper = new Piper();

$piper->pipe(function (Context $context) {
    
});

忽略错误

你可以通过在管道步骤中传递常量 Piper::CONTINUE_ON_ERROR 作为第二个参数来忽略由特定步骤生成的错误。

<?php

use SolidWorx\Piper\Piper;

$piper = new Piper();

$piper->pipe(new PlaceOrder(), Piper::CONTINUE_ON_ERROR); // If the PlaceOrder step generates an error, it will be ignored and the process will continue to the next step

测试

要运行单元测试,请执行以下命令

$ vendor/bin/phpunit

贡献

查看 CONTRIBUTING

许可

Piper 是开源软件,许可协议为 MIT 许可协议

请查看 LICENSE 文件以获取完整许可。