No way to count without fetching rows once `Paginator` is gone
Feature Request
| Q | A |
|---|---|
| New Feature | yes |
| RFC | no |
| BC Break | no |
Summary
This is the symmetric counterpart of #12625, fixed by #12627: 3.8 makes it possible to get the rows without the count, but there is still no way to get the count without the rows.
OffsetPaginator::paginate() fetches the rows eagerly, and it is the only public entry point:
// 3.8.x
$items = array_values($this->getResultForOffset(
$query,
$position->getFirstResult(),
$position->getMaxResults(),
$this->fetchJoinCollection,
));
return new WindowPage($items, function () use ($query): int { /* ... */ }, $position);So obtaining a total means paginating a window and throwing the rows away. The only count-only
entry point was Paginator::count(), deprecated in 3.7 and removed in 4.0.
Why it matters
Pagination layers whose contract separates counting from slicing. A very common shape, because the two are needed at different moments:
interface PaginationAdapter
{
public function getTotalCount(): int;
public function getSlice(int $offset, int $length): iterable;
}
final class DoctrineORMAdapter implements PaginationAdapter
{
public function __construct(private readonly Query $query)
{
}
public function getTotalCount(): int
{
// was: (new Paginator($this->query))->count()
// now: paginate() would fetch a window of rows nobody asked for
}
public function getSlice(int $offset, int $length): iterable
{
return (new OffsetPaginator())
->paginate($this->query, new Window($offset, $length))
->getItems();
}
}getSlice() migrates cleanly. getTotalCount() has no migration path at all, although it is the
one that is often called alone.
Clamping the page number. Redirecting to the last page when the requested one is out of range
needs the total before choosing the window to fetch. With paginate() only, the first fetch is
always wasted.
Totals without a listing: a "N results match" badge, facet counts, or refusing an export above a threshold.
Caching the total separately from the pages, since it usually changes far less often.
Expected behavior
A count-only entry point, for example:
$total = (new OffsetPaginator(fetchJoinCollection: true))->count($query);The walkers are public, so this can be done by hand — but it means re-implementing
getCountQuery(): hint copying, the CountWalker::HINT_DISTINCT default, choosing between
CountWalker and CountOutputWalker, and unbindUnusedQueryParams(). That is internal logic,
and I had to duplicate it to keep the same number of queries.
Source: doctrine/orm