gbenm/phipes

一个简单的可迭代对象转换库

dev-main 2024-02-04 04:46 UTC

This package is auto-updated.

Last update: 2024-09-04 06:10:56 UTC


README

允许链式转换可迭代对象或构建可重用的管道,同时也易于扩展。

快速开始

转换可迭代对象的一些方法

// (temporal results) iterate many times over the same iterable
$result = array_filter($someIterable, $isOdd);
$result = array_map($mulByThree, $result);
$result = array_map($addTwo, $result);

// iterate many times over the same iterable
$result = array_map($addTwo, array_map($mulByThree, array_filter($someIterable, $isOdd)));

// imperative way
$result = [];
foreach ($someIterable as $item) {
    if ($isOdd($item)) {
        $result[] = $addTwo($mulByThree($item));
    }
}

使用Phipes

仅迭代一次

use Phipes\Pipeline;

// delay computation
$result = Pipeline::for($someIterable)
    ->filter($isOdd)
    ->map($mulByThree)
    ->map($addTwo)
    ->asIterable(); // lazy

$result = Pipeline::for($someIterable)
    ->filter($isOdd)
    ->map($mulByThree)
    ->map($addTwo)
    ->asArray(); // start computing at this point

// Creating a pipeline

$pipeline = Pipeline::builder()
    ->filter($isOdd)
    ->map($mulByThree)
    ->map($addTwo)
    ->build();

$results = $pipeline($someIterable);

$otherResults = $pipeline($someIterable2);

创建一个新的转换器

// by example the map function
/** @param (callable($value, [$key]): mixed) $fn  */
function map(callable $fn): callable
{
    return function (iterable $iterable) use ($fn): iterable {
        foreach ($iterable as $key => $item) {
            yield $key => call_user_func($fn, $item, $key);
        }
    };
}

// now you can use the pipe method or call the result
$result = Pipeline::for($someIterable)
    ->pipe(map(fn ($v) => $v + 1))
    ->asIterable(); // lazy

// alternative
$result = Pipeline::for($someIterable)
    (map(fn ($v) => $v + 1))
    ->asIterable(); // lazy