Pagerfanta Documentation
repository·4.x·Indexed 19 days ago
https://github.com/babdev/pagerfantaA PHP library for calculating and rendering paginated lists across various data providers. It features a flexible AdapterInterface for custom data sources and provides first-party adapters for Doctrine (ORM, DBAL, MongoDB ODM, PHPCR ODM, Collections), Elastica, Solarium, and standard PHP arrays. Pagerfanta includes specialized adapters like CallbackAdapter, ConcatenationAdapter, and TransformingAdapter, with dedicated integrations for the Symfony framework and TYPO3.
What's inside Pagerfanta
- Pagerfanta is a PHP library designed to assist with calculating and rendering paginated lists. It provides support for various data providers, allowing you to manage large datasets by breaking them into manageable pages.
Overview of Pagerfanta features
4.xPagerfanta is a PHP library designed for calculating and rendering paginated lists. It provides a unified way to handle pagination across various data sources.
Key features include:
- PHP Templates: Support for multiple CSS frameworks to render pagination UI.
- Adapters: Support for various data providers and database backends, including:
- ElasticSearch
- Solr
- Doctrine (both ORM and ODM)
- Twig Extension: A dedicated extension for rendering pagers within Twig templates.
Explore Pagerfanta ecosystem integrations
4.xPagerfanta is widely used across the PHP ecosystem. If you are building or maintaining one of the following types of projects, you may find Pagerfanta's patterns or existing integrations relevant:
Content Management & Commerce Platforms
- Ibexa DXP: Digital experience platform (successor to eZ Publish).
- Concrete CMS: Open source CMS.
- Kunstmaan CMS: Symfony-based CMS bundles.
- Sylius: Symfony-based e-commerce platform.
Applications
- shlinkio/shlink: Self-hosted URL shortener.
- wallabag/wallabag: Read-it-later application.
- novosga/novosga: Customer queue management system.
Libraries & SDKs
- league/fractal: Data transformation library for API output.
- friendsofsymfony/elastica-bundle: Elasticsearch integration for Symfony.
- willdurand/hateoas: HATEOAS-compliant REST representation library.
What is a Route Generator in Pagerfanta
4.xA route generator is a mechanism used by Pagerfanta to build URLs for different pages in a paginated list.
At its simplest, a route generator is any
callablethat accepts a single integer parameter$page(representing the target page) and returns astringcontaining the URL for that page.$routeGenerator = static fn (int $page): string => 'http://localhost/blog?page=' . $page;Implement the RouteGeneratorInterface
4.xWhile any callable can work, it is recommended to implement thePagerfanta\RouteGenerator\RouteGeneratorInterfacewhen creating custom route generators. This ensures compatibility and type safety within the Pagerfanta ecosystem.Understand the Pagerfanta View abstraction
4.xPagerfanta uses the
Pagerfanta\View\ViewInterfaceto abstract the rendering of pagination lists. A view is responsible for generating the HTML markup required to display pagination controls.To implement a custom view, you must satisfy the
ViewInterfacewhich requires two methods:render: Generates the markup. It accepts aPagerfantaInterfaceinstance, acallablefor route generation, and an optionalarrayof options.getName: Returns a unique string identifier for the view.
Base Classes for Implementation:
Pagerfanta\View\View: The recommended base class. It handles the logic for calculating which page items should be displayed.Pagerfanta\View\TemplateView: An extension ofViewdesigned for use withPagerfanta\View\Template\TemplateInterfaceinstances (useful for template-based rendering).
<?php namespace Pagerfanta//... (interface definition) interface ViewInterface { public function render(PagerfantaInterface $pagerfanta, callable $routeGenerator, array $options = []): string; public function getName(): string; }Implement the Pagerfanta AdapterInterface
4.xTo use Pagerfanta with a custom data source (such as a database, an API, or an array), you must implement the
Pagerfanta\Adapter\AdapterInterface. This interface acts as the abstraction layer that allows Pagerfanta to interact with your data.Your implementation must provide two core methods:
getNbResults(): Returns the total number of items available in the entire dataset.- Note: If the returned count is less than zero, you should throw a
Pagerfanta\Exception\NotValidResultCountException.
- Note: If the returned count is less than zero, you should throw a
getSlice(int $offset, int $length): Returns aniterablecontaining only the subset of items requested for the current page, starting at the specified$offsetwith a maximum of$lengthitems.
By implementing this interface, your data source becomes compatible with all Pagerfanta pagination features, including different pagination strategies and result transformers.
namespace Pagerfanta\Adapter; use Pagerfanta\Exception\NotValidResultCountException; interface AdapterInterface { /** * Returns the number of results for the list. * * @throws NotValidResultCountException if the number of results is less than zero. */ public function getNbResults(): int; /** * Returns an slice of the results representing the current page of items in the list. */ public function getSlice(int $offset, int $length): iterable; }Implement the TemplateInterface to customize pagination markup
4.xTo create custom HTML markup for your pagination list, you must implement the
Pagerfanta\View\Template\TemplateInterface. This interface acts as an abstraction layer for building the different components of a pagination UI (e.g., containers, page numbers, next/previous buttons, and separators).Key responsibilities of an implementation include:
- Route Generation: Using
setRouteGeneratorto provide a callable orRouteGeneratorInterfaceso the template knows how to build URLs. - Configuration: Using
setOptionsto pass custom data to the template. - Component Rendering: Implementing specific methods for each UI element (e.g.,
container(),page(),nextEnabled(), etc.).
Note that the
container()method is expected to return a string containing a%pages%placeholder, which is replaced by the rendered list of pages.<?php namespace Pagerfanta\View\Template; use Pagerfanta\RouteGenerator\RouteGeneratorInterface; interface TemplateInterface { /** * Sets the route generator used while rendering the template. * * @param callable|RouteGeneratorInterface $routeGenerator */ public function setRouteGenerator(callable $routeGenerator): void; /** * Sets the options for the template, overwriting keys that were previously set. */ public function setOptions(array $options): void; /** * Renders the container for the pagination. * * The %pages% placeholder will be replaced by the rendering of pages. */ public function container(): string; /** * Renders a given page. */ public function page(int $page): string; /** * Renders a given page with a specified text. */ public function pageWithText(int $page, string $text, ?string $rel = null): string; /** * Renders the disabled state of the previous page. */ public function previousDisabled(): string; /** * Renders the enabled state of the previous page. */ public function previousEnabled(int $page): string; /** * Renders the disabled state of the next page. */ public function nextDisabled(): string; /** * Renders the enabled state of the next page. */ public function nextEnabled(int $page): string; /** * Renders the first page. */ public function first(): string; /** * Renders the last page. */ public function last(int $page): string; /** * Renders the current page. */ public function current(int $page): string; /** * Renders the separator between pages. */ public function separator(): string; }- Route Generation: Using
Quickstart: Basic Pagerfanta usage
4.xTo use Pagerfanta, you need to provide an adapter containing your data, instantiate
Pagerfanta, and configure your pagination settings. By default, Pagerfanta returns up to 10 items for the first page if no configuration is provided.<?php use Pagerfanta\ use Pagerfanta\Adapter\ArrayAdapter; use Pagerfanta\Pagerfanta; $adapter = new ArrayAdapter([]); $pagerfanta = new Pagerfanta($adapter); // By default, this will return up to 10 items for the first page of results $currentPageResults = $pagerfanta->getCurrentPageResults();Use Solarium adapter
4.xInstall
pagerfanta/solarium-adapterto paginate results from Solarium. TheSolariumAdapterrequires the Solarium instance and the generated select query object.<?php use Pagerfanta\Solarium\SolariumAdapter; $query = $solarium->createSelect(); $query->setQuery('search term'); $adapter = new SolariumAdapter($solarium, $query);Install specific Pagerfanta adapters
4.xAvailable first-party packages include:
pagerfanta/doctrine-collections-adapter: ForDoctrine\Common\Collections\CollectionandSelectableimplementations.pagerfanta/doctrine-dbal-adapter: For Doctrine DBAL support.pagerfanta/doctrine-mongodb-odm-adapter: For Doctrine MongoDB ODM support.pagerfanta/doctrine-orm-adapter: For Doctrine ORM support.pagerfanta/doctrine-phpcr-odm-adapter: For Doctrine PHPCR ODM support.pagerfanta/elastica-adapter: For Elastica (ElasticSearch PHP client) support.pagerfanta/solarium-adapter: For Solarium (Solr search client) support.pagerfanta/twig: For Twig templating support.
# Example: Install only the Doctrine ORM adapter composer require pagerfanta/doctrine-orm-adapterCustomize Twig pagination templates
4.xWhen creating custom Twig templates, extend
@Pagerfanta/default.html.twigand override specific blocks.Key Blocks:
pager_widget: Use this to change the wrapping HTML for the entire paginator.pager: Contains the structure of the pager (links, separators, etc.). Only extend this if you need to change the logic (e.g., removing ellipsis).
Variables available in the template:
pagerfanta: ThePagerfanta\PagerfantaInterfaceobject.route_generator: APagerfanta\RouteGenerator\RouteGeneratorDecorator(used to generate URLs).options: The options array passed to thepagerfanta()function.start_page/end_page: Calculated range based onproximity.current_page: The current active page.nb_pages: Total number of pages.
Variables available in page blocks (
previous_page_link,page_link,current_page_link,next_page_link):page: The specific page number.path: The generated URL for that page.