ice-cream/pipeline

ice-cream pipeline 用于通过管道传递某些内容,进行处理后再将其传回。

1.0.0 2018-03-26 03:35 UTC

This package is not auto-updated.

Last update: 2024-09-15 05:34:06 UTC


README

Build Status Packagist Maintenance Made With Love

这是管道模式的简单实现,其中某个内容通过一系列类进行处理,最终结果被传出。

  • 需要 PHP 7.2
  • 独立

用途

我想为 Ice cream 框架构建这个工具,它可以在管道中传递对象并对其进行操作,这会很有用。

我还构建了这个工具来学习管道模式及其使用方式,以及其他框架在操作对象时如何使用该模式。

安装

composer require ice-cream/pipeline

文档

您可以在这里查看项目的完整文档

如何使用?

class AddOne {

    public function customHandle(int $number) {
        return $number + 1;
    }

    public function handle(int $number) {
        return $number + 1;
    }
}

class TimesTwo {

    public function customHandle(int $number) {
        return $number * 2;
    }

    public function handle(int $number) {
        return $number * 2;
    }
}

$response = (new Pipeline())
    ->pass(10)
    ->through([
        new AddOne,
        new TimesTwo,
    ])
    ->withMethod('customHandle')
    ->process()
    ->getResponse();

var_dump($response); // => 22

您会注意到这里有一组类,值10通过这两个类传递,并在 getResponse() 中返回。我们不这样做,在 process 中返回响应的原因是您可能想调用一个新的方法:then(),它接受一个闭包,您将在下面的示例中看到。

then(\Closure $func)

在上面的示例基础上,假设您在处理传递的值或对象之后想做一些事情

(new Pipeline())
    ->pass(10)
    ->through([
        new AddOne,
        new TimesTwo,
    ])
    ->withMethod('customHandle')
    ->process()
    ->then(function($response) {
        $response *= 10;

        var_dump($response); // => 220
    });

您不能调用 getResponse,因为这是一个闭包,匿名函数。

如果没有自定义方法怎么办?

(new Pipeline())
    ->pass(10)
    ->through([
        new AddOne,
        new TimesTwo,
    ])
    ->process()
    ->then(function($response) {
        $response *= 10;

        var_dump($response); // => 220
    });

在上面的基础上,我们看到类 AddOneTimesTwo 实现了一个 handle() 方法。如果您没有定义 withMethod(String $string),则默认使用必须实现的 handle 方法;否则将抛出告诉你哪个类未能实现所问方法的 \Exception