beebmx/pipeline

管道化你的代码

1.0.0 2024-06-19 17:29 UTC

This package is auto-updated.

Last update: 2024-09-19 17:58:32 UTC


README

Build Status Total Downloads Latest Stable Version License

管道

此包受 Laravel Pipeline 启发,但不使用 Laravel Container

安装

使用 composer 安装

composer require beebmx/pipeline

用法

pipeline 的基本用法是

use Beebmx\Pipeline\Pipeline;

$string = (new Pipeline)
    ->send('say')
    ->through([
        function($string, $next) {
            $string = $string.' hello';

            return $next($string);
        },
        function($string, $next) {
            $string = $string.' world';

            return $next($string);
        }
    ])->execute();

//$string will be 'say hello world'

重要

你应该始终使用 pipe 变量作为参数调用 $next 回调,以传递给下一个管道或最终结果。

如果你需要使用类而不是闭包,你可以这样做

use Beebmx\Pipeline\Pipeline;

class MyOwnPipe
{
    public function handle($myPipeObject, Closure $next)
    {
        $myPipeObject->process();
 
        return $next($myPipeObject);
    }
}

$result = (new Pipeline)
    ->send($someObject)
    ->through([
        MyOwnPipe::class,
        OtherPipe::class,
    ])->execute();

注意

默认情况下,Pipeline 将触发 handle 方法。

如果你需要在管道类中更改默认的 handle 方法,你可以这样做

use Beebmx\Pipeline\Pipeline;

$result = (new Pipeline)
    ->send($someObject)
    ->via('myOwnMethod')
    ->through([
        MyOwnPipe::class,
        OtherPipe::class,
    ])->execute();

在管道流的末尾,你可以这样结束处理

use Beebmx\Pipeline\Pipeline;

$string = (new Pipeline)
    ->send('say')
    ->through(function($string, $next) {
        $string = $string.' hello';

        return $next($string);
    })->then(function($string) {
        $string = $string.' world';

        return $string;
    });

//$string will be 'say hello world'

然后添加更多 pipes 到管道流程中

use Beebmx\Pipeline\Pipeline;

use Beebmx\Pipeline\Pipeline;

$string = (new Pipeline)
    ->send('say')
    ->through(function($string, $next) {
        $string = $string.' hello';

        return $next($string);
    })->pipe(function($string) {
        $string = $string.' world';

        return $string;
    })->execute();

//$string will be 'say hello world'

测试

composer test

致谢