Paginator
When developing web applications, you often meet with the requirement to print out a restricted number of records on a page. However, mathematics behind pagination can be tricky and that's why you should use Nette\Utils\Paginator.
We instantiate the paginator and set the object's properties like: a number of records per page, the number of current page and the total number of records if it is known.
$paginator = new Nette\Utils\Paginator;
$paginator->setItemCount(356); // the total number of records (e.g., a number of products)
$paginator->setItemsPerPage(30); // the number of records on page
$paginator->setPage(1); // the number of the current page (numbered from one)
The object can be passed to a template and after that we can ask clear questions
if ($paginator->first) ... // is this the first page?
if ($paginator->last) ... // is this the last page?
echo $paginator->page; // current page number
We use the paginator in formulation of a SQL query. Methods getLength()
and getOffset()
return values
used in the clauses LIMIT and OFFSET.
$result = $database->table('products')
->limit($paginator->getLength(), $paginator->getOffset());
If you need pages in reverse order (i.e., the page no. 1 corresponds with the highest offset), you may replace the method
getOffset()
with getCountdownOffset()
.