phootwork/collection
phootwork/collection is a lightweight PHP collection library providing convenient data structures and fluent helpers to work with arrays and iterables. Includes common operations like map/filter/reduce, searching, sorting, and easy conversion between collection types.
Start by installing via Composer: composer require phootwork/collection. The library provides first-class support for List, Set, Map, Queue, and Stack — each implementing PHP’s IteratorAggregate and offering a shared fluent API. Begin with the List collection, the most common type for ordered, index-based data:
use phootwork\collection\List as Collection;
$numbers = new Collection([1, 2, 3, 4, 5]);
// Chainable operations
$result = $numbers
->filter(fn($n) => $n % 2 === 0)
->map(fn($n) => $n * $n)
->toArray(); // [4, 16]
First use case: transforming form input arrays into domain-safe structures (e.g., validating and sanitizing request payloads into typed List<string> or List<int>).
Pipeline-style data processing: Replace verbose foreach loops with expressive, testable chains (e.g., ->filter()->map()->reduce()).
Domain-driven value objects: Wrap API responses or database rows into List<Invoice>, Set<User>, or Map<string, Config> for type safety and consistency.
Pipeline composition: Build reusable collection pipelines as reusable methods or classes:
class UserCollection
{
public static function fromArray(array $rows): Collection {
return new Collection($rows)
->filter(fn($row) => $row['active'] ?? false)
->map(fn($row) => new User($row));
}
}
Early conversion guardrails: Convert at the edges (e.g., service boundaries) to avoid scattered array manipulations. Use ->toArray() or ->toIterable() only when returning from domain logic.
Integration with PSR-7/15: Transform PSR request bodies ($request->getParsedBody()) into collections for validation or mapping:
$data = new Collection($request->getParsedBody());
$validated = $data
->map(fn($v) => trim($v))
->filterKeys(fn($k) => in_array($k, ['email', 'name']));
map, filter, sort, etc.) return new collections — do not mutate in place. Chain carefully to avoid performance traps on large datasets.toArray() may exhaust memory. Consider ->toIterable() for lazy iteration or chunking with ->chunk(100).===) in contains(), unique(), and diff() — ensure types match (e.g., 1 vs '1').->sort() with a comparison callback — but note it’s stable only in PHP 8.0+ (since 8.0+, usort is stable).->map()->filter() chains on large collections — consider consolidating operations or using generators where possible.sum()? The library uses reduce() for aggregation — write $sum = $collection->reduce(fn($carry, $n) => $carry + $n, 0);. Use ->sum() if extended via a helper trait.->each(fn($item) => var_dump($item)) mid-chain to inspect intermediate state without breaking fluency.How can I help you explore Laravel packages today?