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.
zenstruck/collection
A
It really shines with Doctrine ORM, where a custom
default_ - no more loading huge amounts of entities into memory at once:
An
each of these runs its own optimized query:
Features:
The core
Package, Required for
Collections
and
_lazily_.
Creating
The
Source, Implementation
Each implementation can also be constructed directly if you want a specific one.
The API
Filtering
Doctrine-backed collections additionally accept specification objects, which are converted
into a real query instead of filtering in PHP.
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
…
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 bydefault_ - 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 yetAn
EntityResult is an unexecuted query you can pass around and derive from. It is lazy and immutable, soeach 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:
- Collections: A lazy, countable, paginatable
Collectioninterface with implementations
- Pagination: Paginate any collection, with page metadata and lazy page-by-page iteration.
- Doctrine:
- ORM: Lazy, specification-driven repositories with DTO/scalar hydration.
- Batch Processing: Memory-safe iteration/mutation of large result sets.
- Collection Bridge: Filter and paginate
doctrine/collectionsinstances -
- Specifications: Express filters/sorts as objects that are converted into native
- Symfony Integration: Autowire a lazy-first repository for any entity.
- Static Analysis: Fully generic - PHPStan knows what your collections contain.
- Recipes: Worked examples for things that aren't a database.
composer require zenstruck/collectionThe core
Collection API has no dependencies. The following packages unlock the optional integrations:Package, Required for
doctrine/orm (>=2.20.7), ORM and Batch Processingdoctrine/collections, Collection Bridgedoctrine/doctrine-bundle, Symfony Integrationsymfony/expression-language, The [#[ForObject]](#symfony-integration) autowiring attributepagerfanta/pagerfanta, PagerfantaAdapterCollections
Zenstruck\Collection is the interface everything in this package implements. It is an IteratorAggregateand
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 LazyCollectionSource, Implementation
array, ArrayCollectionTraversable, LazyCollectioncallable(): iterable, LazyCollectionDoctrine\Common\Collections\Collection, Collection BridgeZenstruck\Collection, itself (returned as-is)null, empty LazyCollectionEach 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 dieFiltering
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.
NOTELazy vs Eager
Specifications are only understood by Doctrine-backed collections. Passing one toArrayCollection,LazyCollectionor any other in-memory implementation throwsZenstruck\Collection\Exception\InvalidSpecification.
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
…