Pagerfanta Documentation

repository·4.x·Indexed 19 days ago

https://github.com/babdev/pagerfanta

A 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.

Tokens
16.9K
Snippets
49
Records
67
Agent score
64%

What's inside Pagerfanta

  1. Overview of Pagerfanta

    4.x
    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.
  2. Overview of Pagerfanta features

    4.x

    Pagerfanta 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.
  3. Explore Pagerfanta ecosystem integrations

    4.x

    Pagerfanta 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.
  4. What is a Route Generator in Pagerfanta

    4.x

    A 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 callable that accepts a single integer parameter $page (representing the target page) and returns a string containing the URL for that page.

    $routeGenerator = static fn (int $page): string => 'http://localhost/blog?page=' . $page;
  5. Understand the Pagerfanta View abstraction

    4.x

    Pagerfanta uses the Pagerfanta\View\ViewInterface to 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 ViewInterface which requires two methods:

    1. render: Generates the markup. It accepts a PagerfantaInterface instance, a callable for route generation, and an optional array of options.
    2. 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 of View designed for use with Pagerfanta\View\Template\TemplateInterface instances (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;
    }
  6. Implement the Pagerfanta AdapterInterface

    4.x

    To 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:

    1. 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.
    2. getSlice(int $offset, int $length): Returns an iterable containing only the subset of items requested for the current page, starting at the specified $offset with a maximum of $length items.

    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;
    }
  7. Implement the TemplateInterface to customize pagination markup

    4.x

    To 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 setRouteGenerator to provide a callable or RouteGeneratorInterface so the template knows how to build URLs.
    • Configuration: Using setOptions to 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;
    }
  8. Quickstart: Basic Pagerfanta usage

    4.x

    To 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();
  9. Use Solarium adapter

    4.x

    Install pagerfanta/solarium-adapter to paginate results from Solarium. The SolariumAdapter requires 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);
  10. Install specific Pagerfanta adapters

    4.x

    Available first-party packages include:

    • pagerfanta/doctrine-collections-adapter: For Doctrine\Common\Collections\Collection and Selectable implementations.
    • 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-adapter
  11. Customize Twig pagination templates

    4.x

    When creating custom Twig templates, extend @Pagerfanta/default.html.twig and 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: The Pagerfanta\PagerfantaInterface object.
    • route_generator: A Pagerfanta\RouteGenerator\RouteGeneratorDecorator (used to generate URLs).
    • options: The options array passed to the pagerfanta() function.
    • start_page / end_page: Calculated range based on proximity.
    • 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.