sanmai/pipeline
sanmai/pipeline is a lightweight PHP pipeline library to process data through a chain of stages. Compose reusable, testable transformations with clear input/output flow, and plug in custom middleware-like steps for flexible processing in any app.
Collection methods are used to convert a pipeline into an array or to iterate over its elements.
A pipeline is lazy and does not begin processing data until a terminal operation is called. These methods consume the pipeline to produce a final result.
Understanding this is key to using the library effectively. No work is done, and no memory is used by the pipeline itself, until one of these methods is invoked.
Common terminal operations include:
toList() and toAssoc() - Convert to arraysfold() and reduce() - Aggregate to a single valuecount(), min(), max() - Calculate statisticseach() - Iterate and perform side effectsfinalVariance() - Calculate comprehensive statisticstoList()Converts the pipeline to a numerically indexed array, discarding all keys.
Signature: toList(): array
Behavior:
Examples:
// Convert a pipeline to a simple array
$result = take(['a' => 1, 'b' => 2, 'c' => 3])->toList();
// Result: [1, 2, 3]
toAssoc()Converts the pipeline to an associative array, preserving the original keys.
Signature: toAssoc(): array
Behavior:
Examples:
// Preserve key-value associations
$result = take(['a' => 1, 'b' => 2, 'c' => 3])
->map(fn($x) => $x * 2)
->toAssoc();
// Result: ['a' => 2, 'b' => 4, 'c' => 6]
getIterator()Returns an iterator for the pipeline, allowing you to use it in a foreach loop.
Signature: getIterator(): Traversable
Behavior:
IteratorAggregate interface.Examples:
// Using foreach
$pipeline = take(['a' => 1, 'b' => 2]);
foreach ($pipeline as $key => $value) {
echo "$key: $value\n";
}
// Manual iteration
$iterator = take([1, 2, 3])->getIterator();
while ($iterator->valid()) {
echo $iterator->current();
$iterator->next();
}
each()Eagerly iterates over all elements in the pipeline, applying a function to each.
Signature: each(callable $func): void
$func: The function to call for each element.Callback Signature: function(mixed $value, mixed $key): void
Behavior:
Examples:
// Print each value
take([1, 2, 3])->each(fn($x) => print("Value: $x\n"));
// Save to a database
take($users)->each(fn($user) => $user->save());
How can I help you explore Laravel packages today?