knplabs/knp-components
Knp Components is a PHP component library from KnpLabs. It currently includes the Pager component for building flexible, “fancy” pagination and paging adapters. PHPUnit 10/11 supported; install with Composer and run the test suite via composer test.
This tutorial will cover installation and usage examples.
composer require "knplabs/knp-components"
As mentioned in introduction, paginator uses event listeners to paginate the given data. First we will start from the simplest data - array. Lets add some code in index.php and see it in action:
<?php
// file: index.php
require 'vendor/autoload.php';
// usage examples will continue here
use Knp\Component\Pager\Paginator;
use Knp\Component\Pager\ArgumentAccess\RequestArgumentAccess;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\RequestStack;
// end of line and tab definition
define('EOL', php_sapi_name() === 'cli' ? PHP_EOL : '<br/>');
define('TAB', php_sapi_name() === 'cli' ? "\t" : '<span style="margin-left:25px"/>');
$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber(new PaginationSubscriber());
$dispatcher->addSubscriber(new SortableSubscriber());
// here we're using the the default access to arguments, based on Symfony Request
// you can use your preferred way to retrieve them, by implementing ArgumentAccessInterface
$accessor = new RequestArgumentAccess(RequestStack::createFromGlobals());
$paginator = new Paginator($dispatcher, $accessor);
$target = range('a', 'z'); // an array to paginate
// paginate target and generate representation class, it can be overrided by event listener
$pagination = $paginator->paginate($target, 1/*page number*/, 10/*limit per page*/);
echo 'total count: '.$pagination->getTotalItemCount().EOL;
echo 'pagination items of page: '.$pagination->getCurrentPageNumber().EOL;
// iterate items
foreach ($pagination as $item) {
//...
echo TAB.'paginated item: '.$item.EOL;
}
$pagination = $paginator->paginate($target, 3/*page number*/, 10/*limit per page*/);
echo 'pagination items of page: '.$pagination->getCurrentPageNumber().EOL;
// iterate items
foreach ($pagination as $item) {
//...
echo TAB.'paginated item: '.$item.EOL;
}
// limit per page can be omitted, or passed as null. In this case default value will be used.
// some other options can be passed as the 4th argument (see [Configuration](docs/pager/config.md))
$pagination = $paginator->paginate($target, 3/*page number*/, null/*default limit per page will be used*/, ['pageParameterName' => 'section']/*options*/);
$paginator->paginate($target...) will return pagination class, which is by default SlidingPagination it executes a $pagination->renderer callback with all arguments reguired in view template. Its your decision to implement it whatever way you like.
Note: this is the default method. There will be more examples on how to render pagination templates
So if you by default print the pagination you should see something like:
<?php
// continuing in file: index.php
// ...
echo $pagination; // outputs: "override in order to render a template"
Now if we override the renderer callback
<?php
// continuing in file: index.php
// ...
$pagination->renderer = function ($data) {
return EOL.TAB.'page range: '.implode(' ', $data['pagesInRange']).EOL;
};
echo $pagination; // outputs: "page range: 1 2 3"
It is not uncommonly that the result of a database query should be sorted by multiple columns. For example users should be sorted by lastname and by firstname:
$query = $entityManager->createQuery('SELECT u FROM User');
$pagination = $paginator->paginate($query, 1/*page number*/, 20/*limit per page*/, [
'defaultSortFieldName' => ['u.lastname', 'u.firstname'],
'defaultSortDirection' => 'asc',
]);
The Paginator will add an ORDER BY automatically for each attribute for the
defaultSortFieldName option.
You can also filter the result of a database query by multiple columns. For example users should be filtered by lastname or by firstname:
$query = $entityManager->createQuery('SELECT u FROM User');
$pagination = $paginator->paginate($query, 1/*page number*/, 20/*limit per page*/, [
'defaultFilterFields' => ['u.lastname', 'u.firstname'],
]);
If the filterValue parameter is set, the Paginator will add an WHERE condition automatically
for each attribute for the defaultFilterFields option. The conditions are OR-linked.
How can I help you explore Laravel packages today?