123 online 3 members  + Join RP Base  +
FreeTool

collection

by zenstruck  ·  version 2026.11.09  ·  updated 2 days ago

No reviews yet

Downloads
0
Reviews
0
Size
103 KB
Code check
Clean
Licence
MIT
Released
Nov 2026

Iterate, filter and paginate anything - arrays, generators or Doctrine ORM queries - without loading it all into memory.

collection
zenstruck/collection
A Collection interface for iterating, paginating and filtering _any_ set of data - arrays, iterators,
doctrine/collections instances and Doctrine ORM queries - all behind the same API:

use function Zenstruck\collect;

$page = collect($users) // array, iterable, closure or doctrine collection
    ->filter(fn(User $user) => $user->isActive())
    ->map(fn(User $user) => $user->email())
    ->paginate(page: 2, limit: 10)
;

\count($page);       // 10 (the number of items on this page)
$page->totalCount(); // 79 (the total number of items)
$page->lastPage();   // 8

foreach ($page as $email) {
    // ...
}

It really shines with Doctrine ORM, where a custom EntityResult object makes everything _lazy by
default_ - no more loading huge amounts of entities into memory at once:

use Zenstruck\Collection\Doctrine\ORM\EntityResult;

$qb = $em->createQueryBuilder()
    ->select('p')
    ->from(Post::class, 'p')
    ->where('p.status = :status')
    ->setParameter('status', 'published')
;

$published = new EntityResult($qb); // nothing has been executed yet

An EntityResult is an unexecuted query you can pass around and derive from. It is lazy and immutable, so
each of these runs its own optimized query:

\count($published);                       // SELECT COUNT(...)
$published->first();                      // ...LIMIT 1
$published->paginate(page: 2, limit: 10); // a single, paginated query
$published->asArray('id', 'title')->first(); // ['id' => 1, 'title' => '...'] - no entity hydrated

foreach ($published as $post) {
    // ...
}

Features:

  1. Collections: A lazy, countable, paginatable Collection interface with implementations
for arrays, iterables and callables.
  1. Pagination: Paginate any collection, with page metadata and lazy page-by-page iteration.
  2. Doctrine:
  3. ORM: Lazy, specification-driven repositories with DTO/scalar hydration.
  4. Batch Processing: Memory-safe iteration/mutation of large result sets.
  5. Collection Bridge: Filter and paginate doctrine/collections instances -
including relations - without initializing them.
  1. Specifications: Express filters/sorts as objects that are converted into native
queries.
  1. Symfony Integration: Autowire a lazy-first repository for any entity.
  2. Static Analysis: Fully generic - PHPStan knows what your collections contain.
  3. Recipes: Worked examples for things that aren't a database.
Installation
composer require zenstruck/collection

The core Collection API has no dependencies. The following packages unlock the optional integrations:

Package, Required for

doctrine/orm (>=2.20.7), ORM and Batch Processing
doctrine/collections, Collection Bridge
doctrine/doctrine-bundle, Symfony Integration
symfony/expression-language, The [#[ForObject]](#symfony-integration) autowiring attribute
pagerfanta/pagerfanta, PagerfantaAdapter
Collections
Zenstruck\Collection is the interface everything in this package implements. It is an IteratorAggregate
and Countable that adds transformation (filter(), map(), keyBy()), reduction (first(),
find(), reduce()) and pagination - and, where the implementation allows, does all of it
_lazily_.
Creating
The Zenstruck\collect() function wraps any source in the most appropriate implementation:

use function Zenstruck\collect;

collect(['a', 'b']);                 // ArrayCollection
collect(new \ArrayIterator(['a']));  // LazyCollection
collect(fn() => fetch_rows());       // LazyCollection (callback not executed yet)
collect($doctrineCollection);        // DoctrineBridgeCollection
collect();                           // empty LazyCollection

Source, Implementation

array, ArrayCollection
Traversable, LazyCollection
callable(): iterable, LazyCollection
Doctrine\Common\Collections\Collection, Collection Bridge
Zenstruck\Collection, itself (returned as-is)
null, empty LazyCollection

Each implementation can also be constructed directly if you want a specific one.
The API
/** @var Zenstruck\Collection $posts */

// transformations - each returns a new Collection, the original is untouched
$posts->filter(fn(Post $post) => $post->isPublished());
$posts->map(fn(Post $post) => $post->title());
$posts->keyBy(fn(Post $post) => $post->id());
$posts->take(10);    // first 10
$posts->take(10, 5); // 10, starting at offset 5

// reductions
$posts->first();                                          // first item or null
$posts->first($default);                                  // first item or $default
$posts->find(fn(Post $post) => $post->isPublished());     // first match or null
$posts->reduce(fn(int $count, Post $post) => $count + 1, 0);
$posts->isEmpty();
\count($posts);

foreach ($posts as $post) {
    // ...
}

$posts->eager();     // load everything into an ArrayCollection
$posts->paginate();  // see "Pagination" below
$posts->dump();      // dump the items and return $this
$posts->dd();        // dump the items and die

Filtering
filter() and find() take a callable(V,K):bool:

$posts->filter(fn(Post $post, int $key) => $post->isPublished());

Doctrine-backed collections additionally accept specification objects, which are converted
into a real query instead of filtering in PHP.

NOTE
Specifications are only understood by Doctrine-backed collections. Passing one to ArrayCollection,
LazyCollection or any other in-memory implementation throws
Zenstruck\Collection\Exception\InvalidSpecification.
Lazy vs Eager
LazyCollection (and the Doctrine implementations) do no work until iterated. Transformations _stay_ lazy -
they wrap the source rather than run it:

```php
$titles = collect(fn() => fetch_rows()) // nothing has run yet
->filter(fn(array $row) => $row['published'])
->map(fn(array $row) => $row['title'])
->take(10)
; // still noth

…