From 46ef2c213c9f50cd67b4115829fc637d96e3f755 Mon Sep 17 00:00:00 2001 From: laminas-bot Date: Wed, 16 Oct 2024 13:12:21 +0000 Subject: [PATCH] Automated deployment: Wed Oct 16 13:12:21 UTC 2024 2.19.0 --- advanced/index.html | 817 +----------- .../stand-alone/index.html | 883 +------------ configuration/index.html | 637 +--------- index.html | 197 +-- installation/index.html | 729 +---------- intro/index.html | 612 +-------- pages/404.html | 189 +-- search/search_index.json | 2 +- sitemap.xml | 33 +- sitemap.xml.gz | Bin 278 -> 262 bytes usage/index.html | 1094 +---------------- v2/advanced/index.html | 715 +++++++++++ .../stand-alone/index.html | 790 ++++++++++++ v2/configuration/index.html | 535 ++++++++ .../images}/usage-rendering-control.png | Bin v2/installation/index.html | 636 ++++++++++ v2/intro/index.html | 519 ++++++++ v2/usage/index.html | 1001 +++++++++++++++ 18 files changed, 4319 insertions(+), 5070 deletions(-) create mode 100644 v2/advanced/index.html create mode 100644 v2/application-integration/stand-alone/index.html create mode 100644 v2/configuration/index.html rename {images => v2/images}/usage-rendering-control.png (100%) create mode 100644 v2/installation/index.html create mode 100644 v2/intro/index.html create mode 100644 v2/usage/index.html diff --git a/advanced/index.html b/advanced/index.html index 8381322c..4a0d185f 100644 --- a/advanced/index.html +++ b/advanced/index.html @@ -1,814 +1,15 @@ - - + + - - - - - - - - - - - - - - Advanced Usage - laminas-paginator - Laminas Docs - - - + Redirecting... + + + + - - - - - - -
-
-
- - -
-

- Components - - - laminas-paginator - -

-
- - - -
-
-
- - -
-
-
- - - - - - - - - - - - - - - - - - - - - - -

Reference

- - -

Advanced usage

-

Using the Paginator Adapter Plugin Manager

-

laminas-paginator ships with a plugin manager for adapters, Laminas\Paginator\AdapterPluginManager. -The plugin manager can be used to retrieve adapters. -Since most adapters require constructor arguments, they may be passed as the second argument to the get() method in the same order they appear in the constructor.

-

Examples

-
use Laminas\Paginator\Adapter;
-use Laminas\Paginator\AdapterPluginManager;
-
-$pluginManager = new AdapterPluginManager();
-
-// Get an array adapter for an array of items
-$arrayAdapter = $pluginManager->get(Adapter\ArrayAdapter::class, [$arrayOfItems]);
-
-// Get a DbSelect adapter based on a Laminas\Db\Sql\Select instance and a DB adapter:
-$dbSelectAdapter = $pluginManager->get(Adapter\DbSelect::class, [
-    $select,
-    $dbAdapter
-]);
-
-// Get a DbTableGateway adapter based on a Laminas\Db\TableGateway\TableGateway instance:
-$dbTDGAdapter = $pluginManager->get(Adapter\DbTableGateway::class, [$tableGateway]);
-
-// Get an Iterator adapter based on an iterator:
-$iteratorAdapter = $pluginManager->get(Adapter\Iterator::class, [$iterator]);
-
-

Note: the laminas-db-based adapters are deprecated since version 2.10.0.

-
-

Custom data source adapters

-

At some point you may run across a data type that is not covered by the packaged -adapters. In this case, you will need to write your own.

-

To do so, you must implement Laminas\Paginator\Adapter\AdapterInterface. There -are two methods required to do this:

-
    -
  • count() : int
  • -
  • getItems(int $offset, int $itemCountPerPage) | array
  • -
-

Additionally, you'll typically implement a constructor that takes your data -source as a parameter.

-

If you've ever used the SPL interface Countable, -you're familiar with count(). As used with laminas-paginator, this is the total -number of items in the data collection; Laminas\Paginator\Paginator::countAllItems -proxies to this method.

-

When retrieving items for the current page, Laminas\Paginator\Paginator calls on -your adapter's getItems() method, providing it with an offset and the number -of items to display per page; your job is to return the appropriate slice of -data. For an array, that would be:

-
return array_slice($this->array, $offset, $itemCountPerPage);
-

Take a look at the packaged adapters for ideas of how you might go about -implementing your own.

-

Registering Your Adapter with the Plugin Manager

-
-

Available since version 2.10.0.

-
-

If you want to register your adapter with the Laminas\Pagiantor\AdapterPluginManager, you can do so via configuration. -The "paginators" configuration key can contain standard laminas-servicemanager-style configuration.

-

One possibility is to add it to the config/autoload/global.php file:

-
return [
-    // ...
-    'paginators' => [
-        'factories' => [
-            YourCustomPaginationAdapter::class => YourCustomPaginationAdapterFactory::class,
-        ],
-    ],
-];
-

This allows you to retrieve the AdapterPluginManager in a factory, and then pull your adapter from it. -As an example, consider the following factory:

-
use Laminas\Paginator\AdapterPluginManager;
-use Laminas\Paginator\Paginator;
-use Psr\Container\ContainerInterface;
-
-class SomeServiceFactory
-{
-    public function __invoke(ContainerInterface $container)
-    {
-        $paginators = $container->get(AdapterPluginManager::class);
-        $paginator  = new Paginator($paginators->get(YourCustomPaginatorAdapter::class));
-        // ...
-    }
-}
-

Custom scrolling styles

-

Creating your own scrolling style requires that you implement -Laminas\Paginator\ScrollingStyle\ScrollingStyleInterface, which defines a single -method:

-
getPages(Paginator $paginator, int $pageRange = null) : array
-

This method should calculate a lower and upper bound for page numbers within the -range of so-called "local" pages (that is, pages that are nearby the current -page).

-

Unless it extends another scrolling style (see -Laminas\Paginator\ScrollingStyle\Elastic for an example), your custom scrolling -style will inevitably end with something similar to the following line of code:

-
return $paginator->getPagesInRange($lowerBound, $upperBound);
-

There's nothing special about this call; it's merely a convenience method to -check the validity of the lower and upper bound and return an array with the range -to the paginator.

-

When you're ready to use your new scrolling style, you'll need to notif -Laminas\Paginator\Paginator:

-
use My\Paginator\ScrollingStyle;
-use Laminas\Paginator\Paginator;
-use Laminas\ServiceManager\Factory\InvokableFactory;
-
-$manager = Paginator::getScrollingStyleManager();
-$manager->setAlias('my-style', ScrollingStyle::class);
-$manager->setFactory(ScrollingStyle::class, InvokableFactory::class);
-

Caching features

-
-

Installation Requirements

-

The caching features depends on the laminas-cache component, so be sure to have -it installed before getting started:

-
$ composer require laminas/laminas-cache
-
-

Laminas\Paginator\Paginator can be told to cache the data it has already used, -preventing the adapter from fetching on next request. To tell -paginator to automatically cache the adapter's data, pass a pre-configured -laminas-cache adapter -to the static setCache() method:

-
use Laminas\Cache\StorageFactory;
-use Laminas\Paginator\Paginator;
-
-$cache = StorageFactory::adapterFactory('filesystem', [
-    'cache_dir' => '/tmp',
-    'ttl'       => 3600,
-    'plugins'   => [ 'serializer' ],
-]);
-Paginator::setCache($cache);
-

As long as the Paginator class has been seeded with a cache storage object, -the data any instance generates will be cached. If you want to disable caching, call -setCacheEnabled() with a boolean false on a concrete instance:

-
use Laminas\Paginator\Paginator;
-
-// $cache is a Laminas\Cache\Storage\StorageInterface instance
-Paginator::setCache($cache);
-
-// ... later on the script:
-$paginator->setCacheEnabled(false);
-// cache is now disabled for this instance.
-

When a cache is set, data are automatically stored in it and pulled out from it. -It then can be useful to empty the cache manually. You can get this done by -calling clearPageItemCache($pageNumber). If you don't pass any parameter, the -whole cache will be empty. You can optionally pass a parameter representing the -page number to empty in the cache:

-
use Laminas\Paginator\Paginator;
-
-// $cache is a Laminas\Cache\Storage\StorageInterface instance
-Paginator::setCache($cache);
-
-// $paginator is a fully configured Paginator instance:
-$items = $paginator->getCurrentItems();
-
-$page3Items = $paginator->getItemsByPage(3);
-// page 3 is now in cache
-
-// clear the cache of the results for page 3
-$paginator->clearPageItemCache(3);
-
-// clear all the cache data
-$paginator->clearPageItemCache();
-

Changing the item count per page will empty the whole cache as it would have -become invalid:

-
use Laminas\Paginator\Paginator;
-
-// $cache is a Laminas\Cache\Storage\StorageInterface instance
-Paginator::setCache($cache);
-
-// Fetch some items from an instance:
-$items = $paginator->getCurrentItems();
-
-// Changing item count flushes the cache:
-$paginator->setItemCountPerPage(2);
-

It is also possible to see the data in cache and ask for it directly. -getPageItemCache() can be used for that:

-
use Laminas\Paginator\Paginator;
-
-// $cache is a Laminas\Cache\Storage\StorageInterface instance
-Paginator::setCache($cache);
-
-// Set the item count:
-$paginator->setItemCountPerPage(3);
-
-// Fetch some items:
-$items = $paginator->getCurrentItems();
-$otherItems = $paginator->getItemsPerPage(4);
-
-// See the cached items as a two-dimensional array:
-var_dump($paginator->getPageItemCache());
- - - - - - - - - -
- -
-
- - - - - - - - - - - - + +Redirecting... - - diff --git a/application-integration/stand-alone/index.html b/application-integration/stand-alone/index.html index e0e03c29..1a7e40db 100644 --- a/application-integration/stand-alone/index.html +++ b/application-integration/stand-alone/index.html @@ -1,880 +1,15 @@ - - + + - - - - - - - - - - - - - - Stand-Alone - laminas-paginator - Laminas Docs - - - + Redirecting... + + + + - - - - - - -
-
-
- - -
-

- Components - - - laminas-paginator - -

-
- - - -
-
-
- - -
-
-
- - - - - - - -
-
On this page
- -
- - - - - - - - - - - - - - -

Application Integration

- - -

Stand-Alone

-

The paginator can also be used stand-alone, outside of a Mezzio or laminas-mvc -application.

-

The example uses the following directory structure:

-
example-app/
-|-- public/
-|   `-- index.php
-|-- templates/
-|   `-- pagination-control.phtml
-`-- vendor
-    `-- …
-

Create and Configure Paginator

-

Create a paginator and a related adapter, -set the item count for one page and the current page number in public/index.php:

-
// Create paginator
-$paginator = new Laminas\Paginator\Paginator(
-    new Laminas\Paginator\Adapter\ArrayAdapter($albums)
-);
-
-// Configure paginator
-$paginator->setItemCountPerPage(4);
-$paginator->setCurrentPageNumber((int) ($_GET['page'] ?? 1));
- -
Example Data - -
$albums = [
-    [
-        'artist' => 'David Bowie',
-        'title'  => 'The Next Day (Deluxe Version)',
-    ],
-    [
-        'artist' => 'Bastille',
-        'title'  => 'Bad Blood',
-    ],
-    [
-        'artist' => 'Bruno Mars',
-        'title'  => 'Unorthodox Jukebox',
-    ],
-    [
-        'artist' => 'Emeli Sandé',
-        'title'  => 'Our Version of Events (Special Edition)',
-    ],
-    [
-        'artist' => 'Bon Jovi',
-        'title'  => 'What About Now (Deluxe Version)',
-    ],
-    [
-        'artist' => 'Justin Timberlake',
-        'title'  => 'The 20/20 Experience (Deluxe Version)',
-    ],
-    [
-        'artist' => 'Bastille',
-        'title'  => 'Bad Blood (The Extended Cut)',
-    ],
-    [
-        'artist' => 'P!nk',
-        'title'  => 'The Truth About Love',
-    ],
-    [
-        'artist' => 'Sound City - Real to Reel',
-        'title'  => 'Sound City - Real to Reel',
-    ],
-    [
-        'artist' => 'Jake Bugg',
-        'title'  => 'Jake Bugg',
-    ],
-];
- - -
- -

Output Pure Data

-

The data of each sub-array is returned by iteration over the paginator:

-
foreach ($paginator as $item) {
-    var_dump($item['artist']); // "Bon Jovi", "Justin Timberlake", …
-    var_dump($item['title']); // "What About Now (Deluxe Version)", "The 20/20 Experience (Deluxe Version)", …
-}
-

Retrieving the current status data of the paginator:

-
var_dump($paginator->getPages()->previous); // 1
-var_dump($paginator->getPages()->next); // 3
-

Usage with laminas-view

-

Create View Script

-

Create a view script in -templates/pagination-control.phtml:

-
<?php
-/**
- * @var Laminas\View\Renderer\PhpRenderer $this
- * @var int                               $pageCount
- * @var int                               $previous
- * @var int                               $next
- * @var int                               $current
- * @var array<int, int>                   $pagesInRange
- */
-?>
-
-<?php if ($pageCount): ?>
-    <nav aria-label="Page navigation example">
-        <ul class="pagination">
-        <!-- Previous page link -->
-        <?php if (isset($previous)): ?>
-            <li class="page-item">
-                <a class="page-link" href="index.php?page=<?= $previous ?>">Previous</a>
-            </li>
-        <?php else: ?>
-            <li class="page-item disabled">
-                <a class="page-link" href="#" tabindex="-1" aria-disabled="true">Previous</a>
-            </li>
-        <?php endif; ?>
-
-        <!-- Numbered page links -->
-        <?php foreach ($pagesInRange as $page): ?>
-            <?php if ($page !== $current): ?>
-                <li class="page-item">
-                    <a class="page-link" href="index.php?page=<?= $page ?>">
-                        <?= $page ?>
-                    </a>
-                </li>
-            <?php else: ?>
-                <!-- Current page -->
-                <li class="page-item active" aria-current="page">
-                    <a class="page-link" href="#"><?= $page ?> <span class="sr-only">(current)</span></a>
-                </li>
-            <?php endif; ?>
-        <?php endforeach; ?>
-
-        <!-- Next page link -->
-        <?php if (isset($this->next)): ?>
-            <li class="page-item">
-                <a class="page-link" href="index.php?page=<?= $next ?>">Next</a>
-            </li>
-        <?php else: ?>
-            <li class="page-item disabled">
-                <a class="page-link" href="#" tabindex="-1" aria-disabled="true">Next</a>
-            </li>
-        <?php endif; ?>
-        </ul>
-    </nav>
-<?php endif; ?>
-

Setup

-

Set a resolver for templates -and set template for the related view helper -in public/index.php:

-
// Create template resolver
-$templateResolver = new Laminas\View\Resolver\TemplatePathStack([
-    'script_paths' => [__DIR__ . '/../templates'],
-]);
-
-// Setup renderer
-/** @var Laminas\View\Renderer\PhpRenderer $renderer */
-$renderer = $paginator->getView();
-$renderer->setResolver($templateResolver);
-
-// Set template for related view helper
-$renderer->plugin('paginationControl')->setDefaultViewPartial('pagination-control');
-

Render Output

-
echo $paginator->render();
-

Output:

-
<nav aria-label="Page navigation example">
-    <ul class="pagination">
-        <!-- Previous page link -->
-        <li class="page-item">
-            <a class="page-link" href="index.php?page=1">Previous</a>
-        </li>
-
-        <!-- Numbered page links -->
-        <li class="page-item">
-            <a class="page-link" href="index.php?page=1">
-                1
-            </a>
-        </li>
-        <!-- Current page -->
-        <li class="page-item active" aria-current="page">
-            <a class="page-link" href="#">2 <span class="sr-only">(current)</span></a>
-        </li>
-        <li class="page-item">
-            <a class="page-link" href="index.php?page=3">
-                3
-            </a>
-        </li>
-
-        <!-- Next page link -->
-        <li class="page-item">
-            <a class="page-link" href="index.php?page=3">Next</a>
-        </li>
-    </ul>
-</nav>
- -
Show full code example - -
<?php
-
-require_once __DIR__ . '/../vendor/autoload.php';
-
-$albums = [
-    [
-        'artist' => 'David Bowie',
-        'title'  => 'The Next Day (Deluxe Version)',
-    ],
-    [
-        'artist' => 'Bastille',
-        'title'  => 'Bad Blood',
-    ],
-    [
-        'artist' => 'Bruno Mars',
-        'title'  => 'Unorthodox Jukebox',
-    ],
-    [
-        'artist' => 'Emeli Sandé',
-        'title'  => 'Our Version of Events (Special Edition)',
-    ],
-    [
-        'artist' => 'Bon Jovi',
-        'title'  => 'What About Now (Deluxe Version)',
-    ],
-    [
-        'artist' => 'Justin Timberlake',
-        'title'  => 'The 20/20 Experience (Deluxe Version)',
-    ],
-    [
-        'artist' => 'Bastille',
-        'title'  => 'Bad Blood (The Extended Cut)',
-    ],
-    [
-        'artist' => 'P!nk',
-        'title'  => 'The Truth About Love',
-    ],
-    [
-        'artist' => 'Sound City - Real to Reel',
-        'title'  => 'Sound City - Real to Reel',
-    ],
-    [
-        'artist' => 'Jake Bugg',
-        'title'  => 'Jake Bugg',
-    ],
-];
-
-// Create paginator
-$paginator = new Laminas\Paginator\Paginator(
-    new Laminas\Paginator\Adapter\ArrayAdapter($albums)
-);
-$paginator->setItemCountPerPage(4);
-$paginator->setCurrentPageNumber((int) ($_GET['page'] ?? 1));
-
-// Create template resolver
-$templateResolver = new Laminas\View\Resolver\TemplatePathStack([
-    'script_paths' => [__DIR__ . '/../templates'],
-]);
-
-// Setup renderer
-/** @var Laminas\View\Renderer\PhpRenderer $renderer */
-$renderer = $paginator->getView();
-$renderer->setResolver($templateResolver);
-
-// Set template for related view helper
-$renderer->plugin('paginationControl')->setDefaultViewPartial('pagination-control');
-
-// Render output
-echo $paginator->render();
- - -
- - - - - - - - - -
- -
-
- - - - - - - - - - - - + +Redirecting... - - diff --git a/configuration/index.html b/configuration/index.html index 0856cd8b..7eff89c3 100644 --- a/configuration/index.html +++ b/configuration/index.html @@ -1,634 +1,15 @@ - - + + - - - - - - - - - - - - - - Configuration - laminas-paginator - Laminas Docs - - - + Redirecting... + + + + - - - - - - -
-
-
- - -
-

- Components - - - laminas-paginator - -

-
- - - -
-
-
- - -
-
-
- - - - - - - - - - - - - - - - - - - - -

Reference

- - -

Configuration

-

Laminas\Paginator has several configuration methods that can be called:

-
- - - - - - - - - - - - - - - - - - - - - - - - -
Method signatureDescription
setCurrentPageNumber(int $page) : voidSets the current page number (default 1).
setItemCountPerPage(int $count) : voidSets the maximum number of items to display on a page (default 10).
setPageRange(int $range) : voidSets the number of items to display in the pagination control (default 10). Note: Most of the time this number will be adhered to exactly, but scrolling styles do have the option of only using it as a guideline or starting value (e.g., Elastic).
setView(Laminas\View\Renderer\RendererInterface $view) : voidSets the view instance, for rendering convenience.
- - - - - - - - - -
- -
-
- - - - - - - - - - - - + +Redirecting... - - diff --git a/index.html b/index.html index 9f5416fd..7a1dc392 100644 --- a/index.html +++ b/index.html @@ -9,7 +9,9 @@ - + + + @@ -82,17 +84,6 @@ - -
-
- -
-
- API Tools
- Build RESTful APIs in Minutes -
-
-
@@ -132,94 +123,51 @@ - - - - - - - - - - + - - - - - - - - - + - - - - - - - - - + - - - - + + - @@ -333,7 +281,7 @@

Support

- - - - - - - + - - - - - - - - - + - - - - - - - - - + - - - - + + - @@ -496,7 +401,7 @@
Laminas
  • Laminas Project The new foundation for the community-supported, open source continuation of Zend Framework
  • Laminas Components and MVC Components and MVC for enterprise applications
  • Mezzio PSR-15 middleware in minutes
  • -
  • Laminas API Tools Build RESTful APIs in minutes
  • +
  • Maintenance Overview Current maintenance status of Laminas & Mezzio packages
  • @@ -592,6 +497,6 @@ diff --git a/installation/index.html b/installation/index.html index 21a0f59a..f91041e8 100644 --- a/installation/index.html +++ b/installation/index.html @@ -1,726 +1,15 @@ - - + + - - - - - - - - - - - - - - Installation - laminas-paginator - Laminas Docs - - - + Redirecting... + + + + - - - - - - -
    -
    -
    - - -
    -

    - Components - - - laminas-paginator - -

    -
    - - - -
    -
    -
    - - -
    -
    -
    - - - - - - - - - - - - -

    Installation

    - - - -

    Standard Installation

    -

    To install the library use Composer:

    -
    $ composer require laminas/laminas-paginator
    - - - -

    - Installation for a - Mezzio - or - laminas-mvc - Application -

    - -

    Installation and Automated Configuration

    -

    - The laminas-component-installer - is the recommended installation method when using in - a Mezzio-based - or - a laminas-mvc-based application. - It will automatically inject - the config-provider - or - the module - in the configuration during the installation process. -

    - -
    -

    Installation Requirements

    -

    - The following descriptions depends on the laminas-component-installer component, - so be sure to have it installed before getting started. -

    - -

    Global Installation

    -

    - With a global installation - of laminas-component-installer it can be used for all projects without a - reinstallation. -

    -
    $ composer global require laminas/laminas-component-installer
    -

    As Development Dependency

    -
    $ composer require --dev laminas/laminas-component-installer
    -
    - -

    Install laminas-paginator and Inject Configuration

    -

    To install the library use Composer:

    -
    $ composer require laminas/laminas-paginator
    -

    - This will install an initial set of dependencies and it will also prompt to - inject the component configuration. -

    -
      - -
    • For a Mezzio application, choose config/config.php.
    • - - -
    • For a laminas-mvc application, choose either modules.config.php or application.config.php.
    • - -
    -

    - If additional dependencies are to be installed, the option for other packages - can be remembered. -

    - -
    Installation and Manual Configuration -

    - If the installer is not used, the manual configuration is needed to add the - component to the application. -

    - -

    Install laminas-paginator

    -

    To install the library use Composer:

    -
    $ composer require laminas/laminas-paginator
    - - -

    Manual Configuration for a Mezzio-based Application

    -

    - Add the configuration provider of laminas-paginator to the configuration file, - e.g. config/config.php: -

    - -
    
    -$aggregator = new Laminas\ConfigAggregator\ConfigAggregator([
    -    // …
    -    Mezzio\ConfigProvider::class,
    -    Mezzio\Router\ConfigProvider::class,
    -    Laminas\Paginator\ConfigProvider, // Add this line
    -    // …
    -]);
    -
    - - - -

    Manual Configuration for a laminas-mvc-based Application

    -

    - Add laminas-paginator as component at the top of the configuration file for - modules, e.g. config/modules.config.php: -

    - -
    
    -return [
    -    'Laminas\Paginator\Module', // Add this line
    -    'Laminas\Router',
    -    'Laminas\Session',
    -    'Laminas\Validator',
    -    'Application',
    -];
    -
    - -
    - - - - - - - - - - - - -
    - -
    -
    - - - - - - - - - - - - + +Redirecting... - - diff --git a/intro/index.html b/intro/index.html index dac6f9fe..97c3697a 100644 --- a/intro/index.html +++ b/intro/index.html @@ -1,609 +1,15 @@ - - + + - - - - - - - - - - - - - - Introduction - laminas-paginator - Laminas Docs - - - + Redirecting... + + + + - - - - - - -
    -
    -
    - - -
    -

    - Components - - - laminas-paginator - -

    -
    - - - -
    -
    -
    - - -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - -

    Introduction

    -

    laminas-paginator is a flexible component for paginating collections of data and -presenting that data to users.

    -

    The primary design goals of laminas-paginator are as follows:

    -
      -
    • Paginate arbitrary data, not just relational databases.
    • -
    • Fetch only the results that need to be displayed.
    • -
    • Do not force users to adhere to only one way of displaying data or rendering - pagination controls.
    • -
    • Loosely couple to other Laminas components so that users who wish to - use it independently of laminas-view, laminas-cache, etc. can do so.
    • -
    - - - - - - - - - -
    - -
    -
    - - - - - - - - - - - - + +Redirecting... - - diff --git a/pages/404.html b/pages/404.html index ab72b0fa..dd851e08 100644 --- a/pages/404.html +++ b/pages/404.html @@ -9,7 +9,9 @@ - + + + @@ -82,17 +84,6 @@ - -
    -
    - -
    -
    - API Tools
    - Build RESTful APIs in Minutes -
    -
    -
    @@ -135,92 +126,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -334,92 +239,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -449,7 +268,7 @@
    Laminas
  • Laminas Project The new foundation for the community-supported, open source continuation of Zend Framework
  • Laminas Components and MVC Components and MVC for enterprise applications
  • Mezzio PSR-15 middleware in minutes
  • -
  • Laminas API Tools Build RESTful APIs in minutes
  • +
  • Maintenance Overview Current maintenance status of Laminas & Mezzio packages
  • diff --git a/search/search_index.json b/search/search_index.json index 7d2e1cb5..f560bb04 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"laminas-paginator 🇷🇺 Русским гражданам Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм. У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую. Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите \"Нет войне!\" 🇺🇸 To Citizens of Russia We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism. One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences. You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say \"stop the war!\" laminas-paginator is a flexible component for paginating collections of data and presenting that data to users. Installation Run the following to install this library: $ composer require laminas/laminas-paginator Documentation Browse the documentation online at https://docs.laminas.dev/laminas-paginator/ Support Issues Chat Forum","title":"Home"},{"location":"#laminas-paginator","text":"","title":"laminas-paginator"},{"location":"#_1","text":"Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм. У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую. Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите \"Нет войне!\"","title":"🇷🇺 Русским гражданам"},{"location":"#to-citizens-of-russia","text":"We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism. One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences. You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say \"stop the war!\" laminas-paginator is a flexible component for paginating collections of data and presenting that data to users.","title":"🇺🇸 To Citizens of Russia"},{"location":"#installation","text":"Run the following to install this library: $ composer require laminas/laminas-paginator","title":"Installation"},{"location":"#documentation","text":"Browse the documentation online at https://docs.laminas.dev/laminas-paginator/","title":"Documentation"},{"location":"#support","text":"Issues Chat Forum","title":"Support"},{"location":"advanced/","text":"Advanced usage Using the Paginator Adapter Plugin Manager laminas-paginator ships with a plugin manager for adapters, Laminas\\Paginator\\AdapterPluginManager . The plugin manager can be used to retrieve adapters. Since most adapters require constructor arguments, they may be passed as the second argument to the get() method in the same order they appear in the constructor. Examples use Laminas\\Paginator\\Adapter; use Laminas\\Paginator\\AdapterPluginManager; $pluginManager = new AdapterPluginManager(); // Get an array adapter for an array of items $arrayAdapter = $pluginManager->get(Adapter\\ArrayAdapter::class, [$arrayOfItems]); // Get a DbSelect adapter based on a Laminas\\Db\\Sql\\Select instance and a DB adapter: $dbSelectAdapter = $pluginManager->get(Adapter\\DbSelect::class, [ $select, $dbAdapter ]); // Get a DbTableGateway adapter based on a Laminas\\Db\\TableGateway\\TableGateway instance: $dbTDGAdapter = $pluginManager->get(Adapter\\DbTableGateway::class, [$tableGateway]); // Get an Iterator adapter based on an iterator: $iteratorAdapter = $pluginManager->get(Adapter\\Iterator::class, [$iterator]); Note : the laminas-db-based adapters are deprecated since version 2.10.0. Custom data source adapters At some point you may run across a data type that is not covered by the packaged adapters. In this case, you will need to write your own. To do so, you must implement Laminas\\Paginator\\Adapter\\AdapterInterface . There are two methods required to do this: count() : int getItems(int $offset, int $itemCountPerPage) | array Additionally, you'll typically implement a constructor that takes your data source as a parameter. If you've ever used the SPL interface Countable , you're familiar with count() . As used with laminas-paginator, this is the total number of items in the data collection; Laminas\\Paginator\\Paginator::countAllItems proxies to this method. When retrieving items for the current page, Laminas\\Paginator\\Paginator calls on your adapter's getItems() method, providing it with an offset and the number of items to display per page; your job is to return the appropriate slice of data. For an array, that would be: return array_slice($this->array, $offset, $itemCountPerPage); Take a look at the packaged adapters for ideas of how you might go about implementing your own. Registering Your Adapter with the Plugin Manager Available since version 2.10.0. If you want to register your adapter with the Laminas\\Pagiantor\\AdapterPluginManager , you can do so via configuration. The \"paginators\" configuration key can contain standard laminas-servicemanager-style configuration . One possibility is to add it to the config/autoload/global.php file: return [ // ... 'paginators' => [ 'factories' => [ YourCustomPaginationAdapter::class => YourCustomPaginationAdapterFactory::class, ], ], ]; This allows you to retrieve the AdapterPluginManager in a factory, and then pull your adapter from it. As an example, consider the following factory: use Laminas\\Paginator\\AdapterPluginManager; use Laminas\\Paginator\\Paginator; use Psr\\Container\\ContainerInterface; class SomeServiceFactory { public function __invoke(ContainerInterface $container) { $paginators = $container->get(AdapterPluginManager::class); $paginator = new Paginator($paginators->get(YourCustomPaginatorAdapter::class)); // ... } } Custom scrolling styles Creating your own scrolling style requires that you implement Laminas\\Paginator\\ScrollingStyle\\ScrollingStyleInterface , which defines a single method: getPages(Paginator $paginator, int $pageRange = null) : array This method should calculate a lower and upper bound for page numbers within the range of so-called \"local\" pages (that is, pages that are nearby the current page). Unless it extends another scrolling style (see Laminas\\Paginator\\ScrollingStyle\\Elastic for an example), your custom scrolling style will inevitably end with something similar to the following line of code: return $paginator->getPagesInRange($lowerBound, $upperBound); There's nothing special about this call; it's merely a convenience method to check the validity of the lower and upper bound and return an array with the range to the paginator. When you're ready to use your new scrolling style, you'll need to notif Laminas\\Paginator\\Paginator : use My\\Paginator\\ScrollingStyle; use Laminas\\Paginator\\Paginator; use Laminas\\ServiceManager\\Factory\\InvokableFactory; $manager = Paginator::getScrollingStyleManager(); $manager->setAlias('my-style', ScrollingStyle::class); $manager->setFactory(ScrollingStyle::class, InvokableFactory::class); Caching features Installation Requirements The caching features depends on the laminas-cache component, so be sure to have it installed before getting started: $ composer require laminas/laminas-cache Laminas\\Paginator\\Paginator can be told to cache the data it has already used, preventing the adapter from fetching on next request. To tell paginator to automatically cache the adapter's data, pass a pre-configured laminas-cache adapter to the static setCache() method: use Laminas\\Cache\\StorageFactory; use Laminas\\Paginator\\Paginator; $cache = StorageFactory::adapterFactory('filesystem', [ 'cache_dir' => '/tmp', 'ttl' => 3600, 'plugins' => [ 'serializer' ], ]); Paginator::setCache($cache); As long as the Paginator class has been seeded with a cache storage object, the data any instance generates will be cached. If you want to disable caching, call setCacheEnabled() with a boolean false on a concrete instance: use Laminas\\Paginator\\Paginator; // $cache is a Laminas\\Cache\\Storage\\StorageInterface instance Paginator::setCache($cache); // ... later on the script: $paginator->setCacheEnabled(false); // cache is now disabled for this instance. When a cache is set, data are automatically stored in it and pulled out from it. It then can be useful to empty the cache manually. You can get this done by calling clearPageItemCache($pageNumber) . If you don't pass any parameter, the whole cache will be empty. You can optionally pass a parameter representing the page number to empty in the cache: use Laminas\\Paginator\\Paginator; // $cache is a Laminas\\Cache\\Storage\\StorageInterface instance Paginator::setCache($cache); // $paginator is a fully configured Paginator instance: $items = $paginator->getCurrentItems(); $page3Items = $paginator->getItemsByPage(3); // page 3 is now in cache // clear the cache of the results for page 3 $paginator->clearPageItemCache(3); // clear all the cache data $paginator->clearPageItemCache(); Changing the item count per page will empty the whole cache as it would have become invalid: use Laminas\\Paginator\\Paginator; // $cache is a Laminas\\Cache\\Storage\\StorageInterface instance Paginator::setCache($cache); // Fetch some items from an instance: $items = $paginator->getCurrentItems(); // Changing item count flushes the cache: $paginator->setItemCountPerPage(2); It is also possible to see the data in cache and ask for it directly. getPageItemCache() can be used for that: use Laminas\\Paginator\\Paginator; // $cache is a Laminas\\Cache\\Storage\\StorageInterface instance Paginator::setCache($cache); // Set the item count: $paginator->setItemCountPerPage(3); // Fetch some items: $items = $paginator->getCurrentItems(); $otherItems = $paginator->getItemsPerPage(4); // See the cached items as a two-dimensional array: var_dump($paginator->getPageItemCache());","title":"Advanced Usage"},{"location":"advanced/#advanced-usage","text":"","title":"Advanced usage"},{"location":"advanced/#using-the-paginator-adapter-plugin-manager","text":"laminas-paginator ships with a plugin manager for adapters, Laminas\\Paginator\\AdapterPluginManager . The plugin manager can be used to retrieve adapters. Since most adapters require constructor arguments, they may be passed as the second argument to the get() method in the same order they appear in the constructor.","title":"Using the Paginator Adapter Plugin Manager"},{"location":"advanced/#custom-data-source-adapters","text":"At some point you may run across a data type that is not covered by the packaged adapters. In this case, you will need to write your own. To do so, you must implement Laminas\\Paginator\\Adapter\\AdapterInterface . There are two methods required to do this: count() : int getItems(int $offset, int $itemCountPerPage) | array Additionally, you'll typically implement a constructor that takes your data source as a parameter. If you've ever used the SPL interface Countable , you're familiar with count() . As used with laminas-paginator, this is the total number of items in the data collection; Laminas\\Paginator\\Paginator::countAllItems proxies to this method. When retrieving items for the current page, Laminas\\Paginator\\Paginator calls on your adapter's getItems() method, providing it with an offset and the number of items to display per page; your job is to return the appropriate slice of data. For an array, that would be: return array_slice($this->array, $offset, $itemCountPerPage); Take a look at the packaged adapters for ideas of how you might go about implementing your own.","title":"Custom data source adapters"},{"location":"advanced/#custom-scrolling-styles","text":"Creating your own scrolling style requires that you implement Laminas\\Paginator\\ScrollingStyle\\ScrollingStyleInterface , which defines a single method: getPages(Paginator $paginator, int $pageRange = null) : array This method should calculate a lower and upper bound for page numbers within the range of so-called \"local\" pages (that is, pages that are nearby the current page). Unless it extends another scrolling style (see Laminas\\Paginator\\ScrollingStyle\\Elastic for an example), your custom scrolling style will inevitably end with something similar to the following line of code: return $paginator->getPagesInRange($lowerBound, $upperBound); There's nothing special about this call; it's merely a convenience method to check the validity of the lower and upper bound and return an array with the range to the paginator. When you're ready to use your new scrolling style, you'll need to notif Laminas\\Paginator\\Paginator : use My\\Paginator\\ScrollingStyle; use Laminas\\Paginator\\Paginator; use Laminas\\ServiceManager\\Factory\\InvokableFactory; $manager = Paginator::getScrollingStyleManager(); $manager->setAlias('my-style', ScrollingStyle::class); $manager->setFactory(ScrollingStyle::class, InvokableFactory::class);","title":"Custom scrolling styles"},{"location":"advanced/#caching-features","text":"","title":"Caching features"},{"location":"configuration/","text":"Configuration Laminas\\Paginator has several configuration methods that can be called: Method signature Description setCurrentPageNumber(int $page) : void Sets the current page number (default 1). setItemCountPerPage(int $count) : void Sets the maximum number of items to display on a page (default 10). setPageRange(int $range) : void Sets the number of items to display in the pagination control (default 10). Note: Most of the time this number will be adhered to exactly, but scrolling styles do have the option of only using it as a guideline or starting value (e.g., Elastic). setView(Laminas\\View\\Renderer\\RendererInterface $view) : void Sets the view instance, for rendering convenience.","title":"Configuration"},{"location":"configuration/#configuration","text":"Laminas\\Paginator has several configuration methods that can be called: Method signature Description setCurrentPageNumber(int $page) : void Sets the current page number (default 1). setItemCountPerPage(int $count) : void Sets the maximum number of items to display on a page (default 10). setPageRange(int $range) : void Sets the number of items to display in the pagination control (default 10). Note: Most of the time this number will be adhered to exactly, but scrolling styles do have the option of only using it as a guideline or starting value (e.g., Elastic). setView(Laminas\\View\\Renderer\\RendererInterface $view) : void Sets the view instance, for rendering convenience.","title":"Configuration"},{"location":"installation/","text":"This is only a placeholder. The content of this page can be found under: https://github.com/laminas/documentation-theme/blob/master/theme/pages/installation.html","title":"Installation"},{"location":"intro/","text":"Introduction laminas-paginator is a flexible component for paginating collections of data and presenting that data to users. The primary design goals of laminas-paginator are as follows: Paginate arbitrary data, not just relational databases. Fetch only the results that need to be displayed. Do not force users to adhere to only one way of displaying data or rendering pagination controls. Loosely couple to other Laminas components so that users who wish to use it independently of laminas-view, laminas-cache, etc. can do so.","title":"Introduction"},{"location":"intro/#introduction","text":"laminas-paginator is a flexible component for paginating collections of data and presenting that data to users. The primary design goals of laminas-paginator are as follows: Paginate arbitrary data, not just relational databases. Fetch only the results that need to be displayed. Do not force users to adhere to only one way of displaying data or rendering pagination controls. Loosely couple to other Laminas components so that users who wish to use it independently of laminas-view, laminas-cache, etc. can do so.","title":"Introduction"},{"location":"usage/","text":"Usage Paginating data collections In order to paginate items into pages, Laminas\\Paginator must have a generic way of accessing that data. For that reason, all data access takes place through data source adapters. Several adapters ship with laminas-paginator by default: Adapter Description ArrayAdapter Accepts a PHP array. DbSelect Accepts a Laminas\\Db\\Sql\\Select instance, plus either a Laminas\\Db\\Adapter\\Adapter or Laminas\\Db\\Sql\\Sql instance; paginates rows from a database. DbTableGateway Accepts a Laminas\\Db\\TableGateway\\AbstractTableGateway instance, and optionally additional arguments representing the WHERE, ORDER BY, GROUP BY, and/or HAVING clauases. Iterator Accepts any Iterator instance. NullFill Dummy paginator. To create a paginator instance, you must supply an adapter to the constructor: use Laminas\\Paginator\\Adapter; use Laminas\\Paginator\\Paginator; $paginator = new Paginator(new Adapter\\ArrayAdapter($array)); In the case of the NullFill adapter, in lieu of a data collection you must supply an item count to its constructor. Although the instance is technically usable in this state, in your controller action you'll need to tell the paginator what page number the user requested. This allows advancing through the paginated data. $paginator->setCurrentPageNumber($page); The simplest way to keep track of this value is through a URL parameter. The following is an example laminas-router route configuration: return [ 'routes' => [ 'paginator' => [ 'type' => 'segment', 'options' => [ 'route' => '/list/[page/:page]', 'defaults' => [ 'page' => 1, ], ], ], ], ]; With the above route (and using laminas-mvc controllers), you might set the current page number in your controller action like so: $paginator->setCurrentPageNumber($this->params()->fromRoute('page')); There are other options available; see the Configuration chapter for more on them. Finally, you'll need to assign the paginator instance to your view. If you're using laminas-mvc and laminas-view, you can assign the paginator object to your view model: $vm = new ViewModel(); $vm->setVariable('paginator', $paginator); return $vm; The DbSelect adapter Deprecated The adapter is deprecated since version 2.10.0. Please use the laminas/laminas-paginator-adapter-laminasdb package if you wish to use the laminas-db-based pagination adapters. Installation Requirements The DbSelect adapter depends on the laminas-db component, so be sure to have it installed before getting started: $ composer require laminas/laminas-db Database optimizations Instead of selecting every matching row of a given query, the DbSelect adapter retrieves only the smallest amount of data necessary for displaying the current page. Because of this, a second query is dynamically generated to determine the total number of matching rows. Most adapters receive their datasets directly. However, the DbSelect adapter requires a more detailed explanation regarding the retrieval and count of the data from the database. You do not have to retrieve data from the database prior to using the DbSelect adapter; the adapter will do the retrieval for you, as well as provide a count of total pages. If additional work has to be done on the database results which cannot be expressed via the provided Laminas\\Db\\Sql\\Select , object you must extend the adapter and override the getItems() method. Additionally this adapter does not fetch all records from the database in order to count them. Instead, the adapter manipulates the original query to produce a corresponding COUNT query, and uses the new query to get the number of rows. While this approach requires an extra round-trip to the database, doing so is stillmany times faster than fetching an entire result set and using count() , especially with large collections of data. The database adapter will try and build the most efficient query that will execute on pretty much any modern database. However, depending on your database or even your own schema setup, there might be more efficient ways to get a rowcount. There are two approaches for doing this. The first is to extend the DbSelect adapter and override the count() method: class MyDbSelect extends DbSelect { public function count() { if ($this->rowCount) { return $this->rowCount; } $select = new Select(); $select ->from('item_counts') ->columns(['c'=>'post_count']); $statement = $this->sql->prepareStatementForSqlObject($select); $result = $statement->execute(); $row = $result->current(); $this->rowCount = $row['c']; return $this->rowCount; } } $adapter = new MyDbSelect($query, $adapter); Alternately, you can pass an additional Laminas\\Db\\Sql\\Select object as the fourth constructor argument to the DbSelect adapter to implement a custom count query. For example, if you keep track of the count of blog posts in a separate table, you could achieve a faster count query with the following setup: use Laminas\\Db\\Sql\\Select; use Laminas\\Paginator\\Adapter\\DbSelect; use Laminas\\Paginator\\Paginator; $countQuery = new Select(); $countQuery ->from('item_counts') ->columns([ DbSelect::ROW_COUNT_COLUMN_NAME => 'post_count' ]); $adapter = new DbSelect($query, $dbAdapter, null, $countQuery); $paginator = new Paginator($adapter); Alternatively, the same can be achieved using the provided factory: use Laminas\\Paginator\\Adapter\\DbSelect; use Laminas\\Paginator\\Factory as PaginatorFactory; $countQuery = new Select(); $countQuery ->from('item_counts') ->columns([ DbSelect::ROW_COUNT_COLUMN_NAME => 'post_count' ]); $paginator = PaginatorFactory::factory( [ $query, $dbAdapter, null, $countQuery, ], DbSelect::class ); This approach will probably not give you a huge performance gain on small collections and/or simple select queries. However, with complex queries and large collections, a similar approach could give you a significant performance boost. The DbSelect adapter also supports returning of fetched records using the ResultSet subcomponent of laminas-db . You can override the concrete ResultSet implementation by passing an object implementing Laminas\\Db\\ResultSet\\ResultSetInterface as the third constructor argument to the DbSelect adapter: use Laminas\\Db\\ResultSet\\HydratingResultSet; use Laminas\\Paginator\\Adapter\\DbSelect; use Laminas\\Paginator\\Paginator; // $objectPrototype is an instance of our custom entity // $hydrator is a custom hydrator for our entity // (implementing Laminas\\Hydrator\\HydratorInterface) $resultSet = new HydratingResultSet($hydrator, $objectPrototype); $adapter = new DbSelect($query, $dbAdapter, $resultSet) $paginator = new Laminas\\Paginator\\Paginator($adapter); Now when we iterate over $paginator we will get instances of our custom entity instead of associative arrays. Rendering pages with view scripts Installation Requirements The rendering with view scripts depends on the laminas-view component, so be sure to have it installed before getting started: $ composer require laminas/laminas-view The view script is used to render the page items (if you're using laminas-paginator to do so) and display the pagination control. Because Laminas\\Paginator\\Paginator implements the SPL interface IteratorAggregate , you can loop over an instance using foreach : <html> <body> <h1>Example</h1> <?php if (count($this->paginator)): ?> <ul> <?php foreach ($this->paginator as $item): ?> <li><?= $item; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> <?= $this->paginationControl( $this->paginator, 'Sliding', 'my_pagination_control', ['route' => 'application/paginator'] ) ?> </body> </html> Notice the view helper call near the end. PaginationControl accepts up to four parameters: the paginator instance, a scrolling style, a view script name, and an array of additional parameters. The second and third parameters are very important. Whereas the view script name is used to determine how the pagination control should look , the scrolling style is used to control how it should behave . Say the view script is in the style of a search pagination control, like the one below: What happens when the user clicks the \"next\" link a few times? Well, any number of things could happen: The current page number could stay in the middle as you click through (as it does on Yahoo!) It could advance to the end of the page range and then appear again on the left when the user clicks \"next\" one more time. The page numbers might even expand and contract as the user advances (or \"scrolls\") through them (as they do on Google). There are four scrolling styles packaged with Laminas: Scrolling style Description All Returns every page. This is useful for dropdown menu pagination controls with relatively few pages. In these cases, you want all pages available to the user at once. Elastic A Google-like scrolling style that expands and contracts as a user scrolls through the pages. Jumping As users scroll through, the page number advances to the end of a given range, then starts again at the beginning of the new range. Sliding A Yahoo!-like scrolling style that positions the current page number in the center of the page range, or as close as possible. This is the default style. The fourth and final parameter is reserved for an optional associative array of variables that you want available in your view (available via $this ). For instance, these values could include extra URL parameters for pagination links. By setting the default view script name, default scrolling style, and view instance, you can eliminate the calls to PaginationControl completely: use Laminas\\Paginator\\Paginator; use Laminas\\View\\Helper\\PaginationControl; Paginator::setDefaultScrollingStyle('Sliding'); PaginationControl::setDefaultViewPartial('my_pagination_control'); When all of these values are set, you can render the pagination control inside your view script by echoing the paginator instance: <?= $this->paginator ?> Using other template engines Of course, it's possible to use laminas-paginator with other template engines. For example, with Smarty you might do the following: $smarty-assign('pages', $paginator->getPages()); You could then access paginator values from a template like so: {$pages.pageCount} Example pagination controls The following example pagination controls will help you get started with laminas-view: Search pagination: <!-- See http://developer.yahoo.com/ypatterns/pattern.php?pattern=searchpagination --> <?php if ($this->pageCount): ?> <div class=\"paginationControl\"> <!-- Previous page link --> <?php if (isset($this->previous)): ?> <a href=\"<?= $this->url($this->route, ['page' => $this->previous]); ?>\"> < Previous </a> | <?php else: ?> <span class=\"disabled\">< Previous</span> | <?php endif; ?> <!-- Numbered page links --> <?php foreach ($this->pagesInRange as $page): ?> <?php if ($page != $this->current): ?> <a href=\"<?= $this->url($this->route, ['page' => $page]); ?>\"> <?= $page; ?> </a> | <?php else: ?> <?= $page; ?> | <?php endif; ?> <?php endforeach; ?> <!-- Next page link --> <?php if (isset($this->next)): ?> <a href=\"<?= $this->url($this->route, ['page' => $this->next]); ?>\"> Next > </a> <?php else: ?> <span class=\"disabled\">Next ></span> <?php endif; ?> </div> <?php endif; ?> Item pagination: <!-- See http://developer.yahoo.com/ypatterns/pattern.php?pattern=itempagination --> <?php if ($this->pageCount): ?> <div class=\"paginationControl\"> <?= $this->firstItemNumber; ?> - <?= $this->lastItemNumber; ?> of <?= $this->totalItemCount; ?> <!-- First page link --> <?php if (isset($this->previous)): ?> <a href=\"<?= $this->url($this->route, ['page' => $this->first]); ?>\"> First </a> | <?php else: ?> <span class=\"disabled\">First</span> | <?php endif; ?> <!-- Previous page link --> <?php if (isset($this->previous)): ?> <a href=\"<?= $this->url($this->route, ['page' => $this->previous]); ?>\"> < Previous </a> | <?php else: ?> <span class=\"disabled\">< Previous</span> | <?php endif; ?> <!-- Next page link --> <?php if (isset($this->next)): ?> <a href=\"<?= $this->url($this->route, ['page' => $this->next]); ?>\"> Next > </a> | <?php else: ?> <span class=\"disabled\">Next ></span> | <?php endif; ?> <!-- Last page link --> <?php if (isset($this->next)): ?> <a href=\"<?= $this->url($this->route, ['page' => $this->last]); ?>\"> Last </a> <?php else: ?> <span class=\"disabled\">Last</span> <?php endif; ?> </div> <?php endif; ?> Dropdown pagination: <?php if ($this->pageCount): ?> <select id=\"paginationControl\" size=\"1\"> <?php foreach ($this->pagesInRange as $page): ?> <?php $selected = ($page == $this->current) ? ' selected=\"selected\"' : ''; ?> <option value=\"<?= $this->url($this->route, ['page' => $page]);?>\"<?= $selected ?>> <?= $page; ?> </option> <?php endforeach; ?> </select> <?php endif; ?> <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js\"> </script> <script type=\"text/javascript\"> $('paginationControl').observe('change', function() { window.location = this.options[this.selectedIndex].value; }) </script> Listing of properties The following options are available to pagination control view scripts: Property Type Description first integer First page number (typically 1). firstItemNumber integer Absolute number of the first item on this page. firstPageInRange integer First page in the range returned by the scrolling style. current integer Current page number. currentItemCount integer Number of items on this page. itemCountPerPage integer Maximum number of items available to each page. last integer Last page number. lastItemNumber integer Absolute number of the last item on this page. lastPageInRange integer Last page in the range returned by the scrolling style. next integer Next page number. pageCount integer Number of pages. pagesInRange array Array of pages returned by the scrolling style. previous integer Previous page number. totalItemCount integer Total number of items.","title":"Usage"},{"location":"usage/#usage","text":"","title":"Usage"},{"location":"usage/#paginating-data-collections","text":"In order to paginate items into pages, Laminas\\Paginator must have a generic way of accessing that data. For that reason, all data access takes place through data source adapters. Several adapters ship with laminas-paginator by default: Adapter Description ArrayAdapter Accepts a PHP array. DbSelect Accepts a Laminas\\Db\\Sql\\Select instance, plus either a Laminas\\Db\\Adapter\\Adapter or Laminas\\Db\\Sql\\Sql instance; paginates rows from a database. DbTableGateway Accepts a Laminas\\Db\\TableGateway\\AbstractTableGateway instance, and optionally additional arguments representing the WHERE, ORDER BY, GROUP BY, and/or HAVING clauases. Iterator Accepts any Iterator instance. NullFill Dummy paginator. To create a paginator instance, you must supply an adapter to the constructor: use Laminas\\Paginator\\Adapter; use Laminas\\Paginator\\Paginator; $paginator = new Paginator(new Adapter\\ArrayAdapter($array)); In the case of the NullFill adapter, in lieu of a data collection you must supply an item count to its constructor. Although the instance is technically usable in this state, in your controller action you'll need to tell the paginator what page number the user requested. This allows advancing through the paginated data. $paginator->setCurrentPageNumber($page); The simplest way to keep track of this value is through a URL parameter. The following is an example laminas-router route configuration: return [ 'routes' => [ 'paginator' => [ 'type' => 'segment', 'options' => [ 'route' => '/list/[page/:page]', 'defaults' => [ 'page' => 1, ], ], ], ], ]; With the above route (and using laminas-mvc controllers), you might set the current page number in your controller action like so: $paginator->setCurrentPageNumber($this->params()->fromRoute('page')); There are other options available; see the Configuration chapter for more on them. Finally, you'll need to assign the paginator instance to your view. If you're using laminas-mvc and laminas-view, you can assign the paginator object to your view model: $vm = new ViewModel(); $vm->setVariable('paginator', $paginator); return $vm;","title":"Paginating data collections"},{"location":"usage/#the-dbselect-adapter","text":"","title":"The DbSelect adapter"},{"location":"usage/#rendering-pages-with-view-scripts","text":"","title":"Rendering pages with view scripts"},{"location":"application-integration/stand-alone/","text":"Stand-Alone The paginator can also be used stand-alone, outside of a Mezzio or laminas-mvc application. The example uses the following directory structure: example-app/ |-- public/ | `-- index.php |-- templates/ | `-- pagination-control.phtml `-- vendor `-- … Create and Configure Paginator Create a paginator and a related adapter , set the item count for one page and the current page number in public/index.php : // Create paginator $paginator = new Laminas\\Paginator\\Paginator( new Laminas\\Paginator\\Adapter\\ArrayAdapter($albums) ); // Configure paginator $paginator->setItemCountPerPage(4); $paginator->setCurrentPageNumber((int) ($_GET['page'] ?? 1)); Example Data $albums = [ [ 'artist' => 'David Bowie', 'title' => 'The Next Day (Deluxe Version)', ], [ 'artist' => 'Bastille', 'title' => 'Bad Blood', ], [ 'artist' => 'Bruno Mars', 'title' => 'Unorthodox Jukebox', ], [ 'artist' => 'Emeli Sandé', 'title' => 'Our Version of Events (Special Edition)', ], [ 'artist' => 'Bon Jovi', 'title' => 'What About Now (Deluxe Version)', ], [ 'artist' => 'Justin Timberlake', 'title' => 'The 20/20 Experience (Deluxe Version)', ], [ 'artist' => 'Bastille', 'title' => 'Bad Blood (The Extended Cut)', ], [ 'artist' => 'P!nk', 'title' => 'The Truth About Love', ], [ 'artist' => 'Sound City - Real to Reel', 'title' => 'Sound City - Real to Reel', ], [ 'artist' => 'Jake Bugg', 'title' => 'Jake Bugg', ], ]; Output Pure Data The data of each sub-array is returned by iteration over the paginator: foreach ($paginator as $item) { var_dump($item['artist']); // \"Bon Jovi\", \"Justin Timberlake\", … var_dump($item['title']); // \"What About Now (Deluxe Version)\", \"The 20/20 Experience (Deluxe Version)\", … } Retrieving the current status data of the paginator : var_dump($paginator->getPages()->previous); // 1 var_dump($paginator->getPages()->next); // 3 Usage with laminas-view Create View Script Create a view script in templates/pagination-control.phtml : <?php /** * @var Laminas\\View\\Renderer\\PhpRenderer $this * @var int $pageCount * @var int $previous * @var int $next * @var int $current * @var array<int, int> $pagesInRange */ ?> <?php if ($pageCount): ?> <nav aria-label=\"Page navigation example\"> <ul class=\"pagination\"> <!-- Previous page link --> <?php if (isset($previous)): ?> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=<?= $previous ?>\">Previous</a> </li> <?php else: ?> <li class=\"page-item disabled\"> <a class=\"page-link\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\">Previous</a> </li> <?php endif; ?> <!-- Numbered page links --> <?php foreach ($pagesInRange as $page): ?> <?php if ($page !== $current): ?> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=<?= $page ?>\"> <?= $page ?> </a> </li> <?php else: ?> <!-- Current page --> <li class=\"page-item active\" aria-current=\"page\"> <a class=\"page-link\" href=\"#\"><?= $page ?> <span class=\"sr-only\">(current)</span></a> </li> <?php endif; ?> <?php endforeach; ?> <!-- Next page link --> <?php if (isset($this->next)): ?> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=<?= $next ?>\">Next</a> </li> <?php else: ?> <li class=\"page-item disabled\"> <a class=\"page-link\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\">Next</a> </li> <?php endif; ?> </ul> </nav> <?php endif; ?> Setup Set a resolver for templates and set template for the related view helper in public/index.php : // Create template resolver $templateResolver = new Laminas\\View\\Resolver\\TemplatePathStack([ 'script_paths' => [__DIR__ . '/../templates'], ]); // Setup renderer /** @var Laminas\\View\\Renderer\\PhpRenderer $renderer */ $renderer = $paginator->getView(); $renderer->setResolver($templateResolver); // Set template for related view helper $renderer->plugin('paginationControl')->setDefaultViewPartial('pagination-control'); Render Output echo $paginator->render(); Output: <nav aria-label=\"Page navigation example\"> <ul class=\"pagination\"> <!-- Previous page link --> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=1\">Previous</a> </li> <!-- Numbered page links --> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=1\"> 1 </a> </li> <!-- Current page --> <li class=\"page-item active\" aria-current=\"page\"> <a class=\"page-link\" href=\"#\">2 <span class=\"sr-only\">(current)</span></a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=3\"> 3 </a> </li> <!-- Next page link --> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=3\">Next</a> </li> </ul> </nav> Show full code example <?php require_once __DIR__ . '/../vendor/autoload.php'; $albums = [ [ 'artist' => 'David Bowie', 'title' => 'The Next Day (Deluxe Version)', ], [ 'artist' => 'Bastille', 'title' => 'Bad Blood', ], [ 'artist' => 'Bruno Mars', 'title' => 'Unorthodox Jukebox', ], [ 'artist' => 'Emeli Sandé', 'title' => 'Our Version of Events (Special Edition)', ], [ 'artist' => 'Bon Jovi', 'title' => 'What About Now (Deluxe Version)', ], [ 'artist' => 'Justin Timberlake', 'title' => 'The 20/20 Experience (Deluxe Version)', ], [ 'artist' => 'Bastille', 'title' => 'Bad Blood (The Extended Cut)', ], [ 'artist' => 'P!nk', 'title' => 'The Truth About Love', ], [ 'artist' => 'Sound City - Real to Reel', 'title' => 'Sound City - Real to Reel', ], [ 'artist' => 'Jake Bugg', 'title' => 'Jake Bugg', ], ]; // Create paginator $paginator = new Laminas\\Paginator\\Paginator( new Laminas\\Paginator\\Adapter\\ArrayAdapter($albums) ); $paginator->setItemCountPerPage(4); $paginator->setCurrentPageNumber((int) ($_GET['page'] ?? 1)); // Create template resolver $templateResolver = new Laminas\\View\\Resolver\\TemplatePathStack([ 'script_paths' => [__DIR__ . '/../templates'], ]); // Setup renderer /** @var Laminas\\View\\Renderer\\PhpRenderer $renderer */ $renderer = $paginator->getView(); $renderer->setResolver($templateResolver); // Set template for related view helper $renderer->plugin('paginationControl')->setDefaultViewPartial('pagination-control'); // Render output echo $paginator->render();","title":"Stand-Alone"},{"location":"application-integration/stand-alone/#stand-alone","text":"The paginator can also be used stand-alone, outside of a Mezzio or laminas-mvc application. The example uses the following directory structure: example-app/ |-- public/ | `-- index.php |-- templates/ | `-- pagination-control.phtml `-- vendor `-- …","title":"Stand-Alone"},{"location":"application-integration/stand-alone/#create-and-configure-paginator","text":"Create a paginator and a related adapter , set the item count for one page and the current page number in public/index.php : // Create paginator $paginator = new Laminas\\Paginator\\Paginator( new Laminas\\Paginator\\Adapter\\ArrayAdapter($albums) ); // Configure paginator $paginator->setItemCountPerPage(4); $paginator->setCurrentPageNumber((int) ($_GET['page'] ?? 1)); Example Data $albums = [ [ 'artist' => 'David Bowie', 'title' => 'The Next Day (Deluxe Version)', ], [ 'artist' => 'Bastille', 'title' => 'Bad Blood', ], [ 'artist' => 'Bruno Mars', 'title' => 'Unorthodox Jukebox', ], [ 'artist' => 'Emeli Sandé', 'title' => 'Our Version of Events (Special Edition)', ], [ 'artist' => 'Bon Jovi', 'title' => 'What About Now (Deluxe Version)', ], [ 'artist' => 'Justin Timberlake', 'title' => 'The 20/20 Experience (Deluxe Version)', ], [ 'artist' => 'Bastille', 'title' => 'Bad Blood (The Extended Cut)', ], [ 'artist' => 'P!nk', 'title' => 'The Truth About Love', ], [ 'artist' => 'Sound City - Real to Reel', 'title' => 'Sound City - Real to Reel', ], [ 'artist' => 'Jake Bugg', 'title' => 'Jake Bugg', ], ];","title":"Create and Configure Paginator"},{"location":"application-integration/stand-alone/#output-pure-data","text":"The data of each sub-array is returned by iteration over the paginator: foreach ($paginator as $item) { var_dump($item['artist']); // \"Bon Jovi\", \"Justin Timberlake\", … var_dump($item['title']); // \"What About Now (Deluxe Version)\", \"The 20/20 Experience (Deluxe Version)\", … } Retrieving the current status data of the paginator : var_dump($paginator->getPages()->previous); // 1 var_dump($paginator->getPages()->next); // 3","title":"Output Pure Data"},{"location":"application-integration/stand-alone/#usage-with-laminas-view","text":"","title":"Usage with laminas-view"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"laminas-paginator 🇷🇺 Русским гражданам Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм. У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую. Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите \"Нет войне!\" 🇺🇸 To Citizens of Russia We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism. One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences. You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say \"stop the war!\" laminas-paginator is a flexible component for paginating collections of data and presenting that data to users. Installation Run the following to install this library: $ composer require laminas/laminas-paginator Documentation Browse the documentation online at https://docs.laminas.dev/laminas-paginator/ Support Issues Chat Forum","title":"Home"},{"location":"#laminas-paginator","text":"","title":"laminas-paginator"},{"location":"#_1","text":"Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм. У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую. Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите \"Нет войне!\"","title":"🇷🇺 Русским гражданам"},{"location":"#to-citizens-of-russia","text":"We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism. One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences. You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say \"stop the war!\" laminas-paginator is a flexible component for paginating collections of data and presenting that data to users.","title":"🇺🇸 To Citizens of Russia"},{"location":"#installation","text":"Run the following to install this library: $ composer require laminas/laminas-paginator","title":"Installation"},{"location":"#documentation","text":"Browse the documentation online at https://docs.laminas.dev/laminas-paginator/","title":"Documentation"},{"location":"#support","text":"Issues Chat Forum","title":"Support"},{"location":"v2/advanced/","text":"Advanced usage Using the Paginator Adapter Plugin Manager laminas-paginator ships with a plugin manager for adapters, Laminas\\Paginator\\AdapterPluginManager . The plugin manager can be used to retrieve adapters. Since most adapters require constructor arguments, they may be passed as the second argument to the get() method in the same order they appear in the constructor. Examples use Laminas\\Paginator\\Adapter; use Laminas\\Paginator\\AdapterPluginManager; $pluginManager = new AdapterPluginManager(); // Get an array adapter for an array of items $arrayAdapter = $pluginManager->get(Adapter\\ArrayAdapter::class, [$arrayOfItems]); // Get a DbSelect adapter based on a Laminas\\Db\\Sql\\Select instance and a DB adapter: $dbSelectAdapter = $pluginManager->get(Adapter\\DbSelect::class, [ $select, $dbAdapter ]); // Get a DbTableGateway adapter based on a Laminas\\Db\\TableGateway\\TableGateway instance: $dbTDGAdapter = $pluginManager->get(Adapter\\DbTableGateway::class, [$tableGateway]); // Get an Iterator adapter based on an iterator: $iteratorAdapter = $pluginManager->get(Adapter\\Iterator::class, [$iterator]); Note : the laminas-db-based adapters are deprecated since version 2.10.0. Custom data source adapters At some point you may run across a data type that is not covered by the packaged adapters. In this case, you will need to write your own. To do so, you must implement Laminas\\Paginator\\Adapter\\AdapterInterface . There are two methods required to do this: count() : int getItems(int $offset, int $itemCountPerPage) | array Additionally, you'll typically implement a constructor that takes your data source as a parameter. If you've ever used the SPL interface Countable , you're familiar with count() . As used with laminas-paginator, this is the total number of items in the data collection; Laminas\\Paginator\\Paginator::countAllItems proxies to this method. When retrieving items for the current page, Laminas\\Paginator\\Paginator calls on your adapter's getItems() method, providing it with an offset and the number of items to display per page; your job is to return the appropriate slice of data. For an array, that would be: return array_slice($this->array, $offset, $itemCountPerPage); Take a look at the packaged adapters for ideas of how you might go about implementing your own. Registering Your Adapter with the Plugin Manager Available since version 2.10.0. If you want to register your adapter with the Laminas\\Pagiantor\\AdapterPluginManager , you can do so via configuration. The \"paginators\" configuration key can contain standard laminas-servicemanager-style configuration . One possibility is to add it to the config/autoload/global.php file: return [ // ... 'paginators' => [ 'factories' => [ YourCustomPaginationAdapter::class => YourCustomPaginationAdapterFactory::class, ], ], ]; This allows you to retrieve the AdapterPluginManager in a factory, and then pull your adapter from it. As an example, consider the following factory: use Laminas\\Paginator\\AdapterPluginManager; use Laminas\\Paginator\\Paginator; use Psr\\Container\\ContainerInterface; class SomeServiceFactory { public function __invoke(ContainerInterface $container) { $paginators = $container->get(AdapterPluginManager::class); $paginator = new Paginator($paginators->get(YourCustomPaginatorAdapter::class)); // ... } } Custom scrolling styles Creating your own scrolling style requires that you implement Laminas\\Paginator\\ScrollingStyle\\ScrollingStyleInterface , which defines a single method: getPages(Paginator $paginator, int $pageRange = null) : array This method should calculate a lower and upper bound for page numbers within the range of so-called \"local\" pages (that is, pages that are nearby the current page). Unless it extends another scrolling style (see Laminas\\Paginator\\ScrollingStyle\\Elastic for an example), your custom scrolling style will inevitably end with something similar to the following line of code: return $paginator->getPagesInRange($lowerBound, $upperBound); There's nothing special about this call; it's merely a convenience method to check the validity of the lower and upper bound and return an array with the range to the paginator. When you're ready to use your new scrolling style, you'll need to notif Laminas\\Paginator\\Paginator : use My\\Paginator\\ScrollingStyle; use Laminas\\Paginator\\Paginator; use Laminas\\ServiceManager\\Factory\\InvokableFactory; $manager = Paginator::getScrollingStyleManager(); $manager->setAlias('my-style', ScrollingStyle::class); $manager->setFactory(ScrollingStyle::class, InvokableFactory::class); Caching features Installation Requirements The caching features depends on the laminas-cache component, so be sure to have it installed before getting started: $ composer require laminas/laminas-cache Laminas\\Paginator\\Paginator can be told to cache the data it has already used, preventing the adapter from fetching on next request. To tell paginator to automatically cache the adapter's data, pass a pre-configured laminas-cache adapter to the static setCache() method: use Laminas\\Cache\\StorageFactory; use Laminas\\Paginator\\Paginator; $cache = StorageFactory::adapterFactory('filesystem', [ 'cache_dir' => '/tmp', 'ttl' => 3600, 'plugins' => [ 'serializer' ], ]); Paginator::setCache($cache); As long as the Paginator class has been seeded with a cache storage object, the data any instance generates will be cached. If you want to disable caching, call setCacheEnabled() with a boolean false on a concrete instance: use Laminas\\Paginator\\Paginator; // $cache is a Laminas\\Cache\\Storage\\StorageInterface instance Paginator::setCache($cache); // ... later on the script: $paginator->setCacheEnabled(false); // cache is now disabled for this instance. When a cache is set, data are automatically stored in it and pulled out from it. It then can be useful to empty the cache manually. You can get this done by calling clearPageItemCache($pageNumber) . If you don't pass any parameter, the whole cache will be empty. You can optionally pass a parameter representing the page number to empty in the cache: use Laminas\\Paginator\\Paginator; // $cache is a Laminas\\Cache\\Storage\\StorageInterface instance Paginator::setCache($cache); // $paginator is a fully configured Paginator instance: $items = $paginator->getCurrentItems(); $page3Items = $paginator->getItemsByPage(3); // page 3 is now in cache // clear the cache of the results for page 3 $paginator->clearPageItemCache(3); // clear all the cache data $paginator->clearPageItemCache(); Changing the item count per page will empty the whole cache as it would have become invalid: use Laminas\\Paginator\\Paginator; // $cache is a Laminas\\Cache\\Storage\\StorageInterface instance Paginator::setCache($cache); // Fetch some items from an instance: $items = $paginator->getCurrentItems(); // Changing item count flushes the cache: $paginator->setItemCountPerPage(2); It is also possible to see the data in cache and ask for it directly. getPageItemCache() can be used for that: use Laminas\\Paginator\\Paginator; // $cache is a Laminas\\Cache\\Storage\\StorageInterface instance Paginator::setCache($cache); // Set the item count: $paginator->setItemCountPerPage(3); // Fetch some items: $items = $paginator->getCurrentItems(); $otherItems = $paginator->getItemsPerPage(4); // See the cached items as a two-dimensional array: var_dump($paginator->getPageItemCache());","title":"Advanced Usage"},{"location":"v2/advanced/#advanced-usage","text":"","title":"Advanced usage"},{"location":"v2/advanced/#using-the-paginator-adapter-plugin-manager","text":"laminas-paginator ships with a plugin manager for adapters, Laminas\\Paginator\\AdapterPluginManager . The plugin manager can be used to retrieve adapters. Since most adapters require constructor arguments, they may be passed as the second argument to the get() method in the same order they appear in the constructor.","title":"Using the Paginator Adapter Plugin Manager"},{"location":"v2/advanced/#custom-data-source-adapters","text":"At some point you may run across a data type that is not covered by the packaged adapters. In this case, you will need to write your own. To do so, you must implement Laminas\\Paginator\\Adapter\\AdapterInterface . There are two methods required to do this: count() : int getItems(int $offset, int $itemCountPerPage) | array Additionally, you'll typically implement a constructor that takes your data source as a parameter. If you've ever used the SPL interface Countable , you're familiar with count() . As used with laminas-paginator, this is the total number of items in the data collection; Laminas\\Paginator\\Paginator::countAllItems proxies to this method. When retrieving items for the current page, Laminas\\Paginator\\Paginator calls on your adapter's getItems() method, providing it with an offset and the number of items to display per page; your job is to return the appropriate slice of data. For an array, that would be: return array_slice($this->array, $offset, $itemCountPerPage); Take a look at the packaged adapters for ideas of how you might go about implementing your own.","title":"Custom data source adapters"},{"location":"v2/advanced/#custom-scrolling-styles","text":"Creating your own scrolling style requires that you implement Laminas\\Paginator\\ScrollingStyle\\ScrollingStyleInterface , which defines a single method: getPages(Paginator $paginator, int $pageRange = null) : array This method should calculate a lower and upper bound for page numbers within the range of so-called \"local\" pages (that is, pages that are nearby the current page). Unless it extends another scrolling style (see Laminas\\Paginator\\ScrollingStyle\\Elastic for an example), your custom scrolling style will inevitably end with something similar to the following line of code: return $paginator->getPagesInRange($lowerBound, $upperBound); There's nothing special about this call; it's merely a convenience method to check the validity of the lower and upper bound and return an array with the range to the paginator. When you're ready to use your new scrolling style, you'll need to notif Laminas\\Paginator\\Paginator : use My\\Paginator\\ScrollingStyle; use Laminas\\Paginator\\Paginator; use Laminas\\ServiceManager\\Factory\\InvokableFactory; $manager = Paginator::getScrollingStyleManager(); $manager->setAlias('my-style', ScrollingStyle::class); $manager->setFactory(ScrollingStyle::class, InvokableFactory::class);","title":"Custom scrolling styles"},{"location":"v2/advanced/#caching-features","text":"","title":"Caching features"},{"location":"v2/configuration/","text":"Configuration Laminas\\Paginator has several configuration methods that can be called: Method signature Description setCurrentPageNumber(int $page) : void Sets the current page number (default 1). setItemCountPerPage(int $count) : void Sets the maximum number of items to display on a page (default 10). setPageRange(int $range) : void Sets the number of items to display in the pagination control (default 10). Note: Most of the time this number will be adhered to exactly, but scrolling styles do have the option of only using it as a guideline or starting value (e.g., Elastic). setView(Laminas\\View\\Renderer\\RendererInterface $view) : void Sets the view instance, for rendering convenience.","title":"Configuration"},{"location":"v2/configuration/#configuration","text":"Laminas\\Paginator has several configuration methods that can be called: Method signature Description setCurrentPageNumber(int $page) : void Sets the current page number (default 1). setItemCountPerPage(int $count) : void Sets the maximum number of items to display on a page (default 10). setPageRange(int $range) : void Sets the number of items to display in the pagination control (default 10). Note: Most of the time this number will be adhered to exactly, but scrolling styles do have the option of only using it as a guideline or starting value (e.g., Elastic). setView(Laminas\\View\\Renderer\\RendererInterface $view) : void Sets the view instance, for rendering convenience.","title":"Configuration"},{"location":"v2/installation/","text":"This is only a placeholder. The content of this page can be found under: https://github.com/laminas/documentation-theme/blob/master/theme/pages/installation.html","title":"Installation"},{"location":"v2/intro/","text":"Introduction laminas-paginator is a flexible component for paginating collections of data and presenting that data to users. The primary design goals of laminas-paginator are as follows: Paginate arbitrary data, not just relational databases. Fetch only the results that need to be displayed. Do not force users to adhere to only one way of displaying data or rendering pagination controls. Loosely couple to other Laminas components so that users who wish to use it independently of laminas-view, laminas-cache, etc. can do so.","title":"Introduction"},{"location":"v2/intro/#introduction","text":"laminas-paginator is a flexible component for paginating collections of data and presenting that data to users. The primary design goals of laminas-paginator are as follows: Paginate arbitrary data, not just relational databases. Fetch only the results that need to be displayed. Do not force users to adhere to only one way of displaying data or rendering pagination controls. Loosely couple to other Laminas components so that users who wish to use it independently of laminas-view, laminas-cache, etc. can do so.","title":"Introduction"},{"location":"v2/usage/","text":"Usage Paginating data collections In order to paginate items into pages, Laminas\\Paginator must have a generic way of accessing that data. For that reason, all data access takes place through data source adapters. Several adapters ship with laminas-paginator by default: Adapter Description ArrayAdapter Accepts a PHP array. DbSelect Accepts a Laminas\\Db\\Sql\\Select instance, plus either a Laminas\\Db\\Adapter\\Adapter or Laminas\\Db\\Sql\\Sql instance; paginates rows from a database. DbTableGateway Accepts a Laminas\\Db\\TableGateway\\AbstractTableGateway instance, and optionally additional arguments representing the WHERE, ORDER BY, GROUP BY, and/or HAVING clauases. Iterator Accepts any Iterator instance. NullFill Dummy paginator. To create a paginator instance, you must supply an adapter to the constructor: use Laminas\\Paginator\\Adapter; use Laminas\\Paginator\\Paginator; $paginator = new Paginator(new Adapter\\ArrayAdapter($array)); In the case of the NullFill adapter, in lieu of a data collection you must supply an item count to its constructor. Although the instance is technically usable in this state, in your controller action you'll need to tell the paginator what page number the user requested. This allows advancing through the paginated data. $paginator->setCurrentPageNumber($page); The simplest way to keep track of this value is through a URL parameter. The following is an example laminas-router route configuration: return [ 'routes' => [ 'paginator' => [ 'type' => 'segment', 'options' => [ 'route' => '/list/[page/:page]', 'defaults' => [ 'page' => 1, ], ], ], ], ]; With the above route (and using laminas-mvc controllers), you might set the current page number in your controller action like so: $paginator->setCurrentPageNumber($this->params()->fromRoute('page')); There are other options available; see the Configuration chapter for more on them. Finally, you'll need to assign the paginator instance to your view. If you're using laminas-mvc and laminas-view, you can assign the paginator object to your view model: $vm = new ViewModel(); $vm->setVariable('paginator', $paginator); return $vm; The DbSelect adapter Deprecated The adapter is deprecated since version 2.10.0. Please use the laminas/laminas-paginator-adapter-laminasdb package if you wish to use the laminas-db-based pagination adapters. Installation Requirements The DbSelect adapter depends on the laminas-db component, so be sure to have it installed before getting started: $ composer require laminas/laminas-db Database optimizations Instead of selecting every matching row of a given query, the DbSelect adapter retrieves only the smallest amount of data necessary for displaying the current page. Because of this, a second query is dynamically generated to determine the total number of matching rows. Most adapters receive their datasets directly. However, the DbSelect adapter requires a more detailed explanation regarding the retrieval and count of the data from the database. You do not have to retrieve data from the database prior to using the DbSelect adapter; the adapter will do the retrieval for you, as well as provide a count of total pages. If additional work has to be done on the database results which cannot be expressed via the provided Laminas\\Db\\Sql\\Select , object you must extend the adapter and override the getItems() method. Additionally this adapter does not fetch all records from the database in order to count them. Instead, the adapter manipulates the original query to produce a corresponding COUNT query, and uses the new query to get the number of rows. While this approach requires an extra round-trip to the database, doing so is stillmany times faster than fetching an entire result set and using count() , especially with large collections of data. The database adapter will try and build the most efficient query that will execute on pretty much any modern database. However, depending on your database or even your own schema setup, there might be more efficient ways to get a rowcount. There are two approaches for doing this. The first is to extend the DbSelect adapter and override the count() method: class MyDbSelect extends DbSelect { public function count() { if ($this->rowCount) { return $this->rowCount; } $select = new Select(); $select ->from('item_counts') ->columns(['c'=>'post_count']); $statement = $this->sql->prepareStatementForSqlObject($select); $result = $statement->execute(); $row = $result->current(); $this->rowCount = $row['c']; return $this->rowCount; } } $adapter = new MyDbSelect($query, $adapter); Alternately, you can pass an additional Laminas\\Db\\Sql\\Select object as the fourth constructor argument to the DbSelect adapter to implement a custom count query. For example, if you keep track of the count of blog posts in a separate table, you could achieve a faster count query with the following setup: use Laminas\\Db\\Sql\\Select; use Laminas\\Paginator\\Adapter\\DbSelect; use Laminas\\Paginator\\Paginator; $countQuery = new Select(); $countQuery ->from('item_counts') ->columns([ DbSelect::ROW_COUNT_COLUMN_NAME => 'post_count' ]); $adapter = new DbSelect($query, $dbAdapter, null, $countQuery); $paginator = new Paginator($adapter); Alternatively, the same can be achieved using the provided factory: use Laminas\\Paginator\\Adapter\\DbSelect; use Laminas\\Paginator\\Factory as PaginatorFactory; $countQuery = new Select(); $countQuery ->from('item_counts') ->columns([ DbSelect::ROW_COUNT_COLUMN_NAME => 'post_count' ]); $paginator = PaginatorFactory::factory( [ $query, $dbAdapter, null, $countQuery, ], DbSelect::class ); This approach will probably not give you a huge performance gain on small collections and/or simple select queries. However, with complex queries and large collections, a similar approach could give you a significant performance boost. The DbSelect adapter also supports returning of fetched records using the ResultSet subcomponent of laminas-db . You can override the concrete ResultSet implementation by passing an object implementing Laminas\\Db\\ResultSet\\ResultSetInterface as the third constructor argument to the DbSelect adapter: use Laminas\\Db\\ResultSet\\HydratingResultSet; use Laminas\\Paginator\\Adapter\\DbSelect; use Laminas\\Paginator\\Paginator; // $objectPrototype is an instance of our custom entity // $hydrator is a custom hydrator for our entity // (implementing Laminas\\Hydrator\\HydratorInterface) $resultSet = new HydratingResultSet($hydrator, $objectPrototype); $adapter = new DbSelect($query, $dbAdapter, $resultSet) $paginator = new Laminas\\Paginator\\Paginator($adapter); Now when we iterate over $paginator we will get instances of our custom entity instead of associative arrays. Rendering pages with view scripts Installation Requirements The rendering with view scripts depends on the laminas-view component, so be sure to have it installed before getting started: $ composer require laminas/laminas-view The view script is used to render the page items (if you're using laminas-paginator to do so) and display the pagination control. Because Laminas\\Paginator\\Paginator implements the SPL interface IteratorAggregate , you can loop over an instance using foreach : <html> <body> <h1>Example</h1> <?php if (count($this->paginator)): ?> <ul> <?php foreach ($this->paginator as $item): ?> <li><?= $item; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> <?= $this->paginationControl( $this->paginator, 'Sliding', 'my_pagination_control', ['route' => 'application/paginator'] ) ?> </body> </html> Notice the view helper call near the end. PaginationControl accepts up to four parameters: the paginator instance, a scrolling style, a view script name, and an array of additional parameters. The second and third parameters are very important. Whereas the view script name is used to determine how the pagination control should look , the scrolling style is used to control how it should behave . Say the view script is in the style of a search pagination control, like the one below: What happens when the user clicks the \"next\" link a few times? Well, any number of things could happen: The current page number could stay in the middle as you click through (as it does on Yahoo!) It could advance to the end of the page range and then appear again on the left when the user clicks \"next\" one more time. The page numbers might even expand and contract as the user advances (or \"scrolls\") through them (as they do on Google). There are four scrolling styles packaged with Laminas: Scrolling style Description All Returns every page. This is useful for dropdown menu pagination controls with relatively few pages. In these cases, you want all pages available to the user at once. Elastic A Google-like scrolling style that expands and contracts as a user scrolls through the pages. Jumping As users scroll through, the page number advances to the end of a given range, then starts again at the beginning of the new range. Sliding A Yahoo!-like scrolling style that positions the current page number in the center of the page range, or as close as possible. This is the default style. The fourth and final parameter is reserved for an optional associative array of variables that you want available in your view (available via $this ). For instance, these values could include extra URL parameters for pagination links. By setting the default view script name, default scrolling style, and view instance, you can eliminate the calls to PaginationControl completely: use Laminas\\Paginator\\Paginator; use Laminas\\View\\Helper\\PaginationControl; Paginator::setDefaultScrollingStyle('Sliding'); PaginationControl::setDefaultViewPartial('my_pagination_control'); When all of these values are set, you can render the pagination control inside your view script by echoing the paginator instance: <?= $this->paginator ?> Using other template engines Of course, it's possible to use laminas-paginator with other template engines. For example, with Smarty you might do the following: $smarty-assign('pages', $paginator->getPages()); You could then access paginator values from a template like so: {$pages.pageCount} Example pagination controls The following example pagination controls will help you get started with laminas-view: Search pagination: <!-- See http://developer.yahoo.com/ypatterns/pattern.php?pattern=searchpagination --> <?php if ($this->pageCount): ?> <div class=\"paginationControl\"> <!-- Previous page link --> <?php if (isset($this->previous)): ?> <a href=\"<?= $this->url($this->route, ['page' => $this->previous]); ?>\"> < Previous </a> | <?php else: ?> <span class=\"disabled\">< Previous</span> | <?php endif; ?> <!-- Numbered page links --> <?php foreach ($this->pagesInRange as $page): ?> <?php if ($page != $this->current): ?> <a href=\"<?= $this->url($this->route, ['page' => $page]); ?>\"> <?= $page; ?> </a> | <?php else: ?> <?= $page; ?> | <?php endif; ?> <?php endforeach; ?> <!-- Next page link --> <?php if (isset($this->next)): ?> <a href=\"<?= $this->url($this->route, ['page' => $this->next]); ?>\"> Next > </a> <?php else: ?> <span class=\"disabled\">Next ></span> <?php endif; ?> </div> <?php endif; ?> Item pagination: <!-- See http://developer.yahoo.com/ypatterns/pattern.php?pattern=itempagination --> <?php if ($this->pageCount): ?> <div class=\"paginationControl\"> <?= $this->firstItemNumber; ?> - <?= $this->lastItemNumber; ?> of <?= $this->totalItemCount; ?> <!-- First page link --> <?php if (isset($this->previous)): ?> <a href=\"<?= $this->url($this->route, ['page' => $this->first]); ?>\"> First </a> | <?php else: ?> <span class=\"disabled\">First</span> | <?php endif; ?> <!-- Previous page link --> <?php if (isset($this->previous)): ?> <a href=\"<?= $this->url($this->route, ['page' => $this->previous]); ?>\"> < Previous </a> | <?php else: ?> <span class=\"disabled\">< Previous</span> | <?php endif; ?> <!-- Next page link --> <?php if (isset($this->next)): ?> <a href=\"<?= $this->url($this->route, ['page' => $this->next]); ?>\"> Next > </a> | <?php else: ?> <span class=\"disabled\">Next ></span> | <?php endif; ?> <!-- Last page link --> <?php if (isset($this->next)): ?> <a href=\"<?= $this->url($this->route, ['page' => $this->last]); ?>\"> Last </a> <?php else: ?> <span class=\"disabled\">Last</span> <?php endif; ?> </div> <?php endif; ?> Dropdown pagination: <?php if ($this->pageCount): ?> <select id=\"paginationControl\" size=\"1\"> <?php foreach ($this->pagesInRange as $page): ?> <?php $selected = ($page == $this->current) ? ' selected=\"selected\"' : ''; ?> <option value=\"<?= $this->url($this->route, ['page' => $page]);?>\"<?= $selected ?>> <?= $page; ?> </option> <?php endforeach; ?> </select> <?php endif; ?> <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js\"> </script> <script type=\"text/javascript\"> $('paginationControl').observe('change', function() { window.location = this.options[this.selectedIndex].value; }) </script> Listing of properties The following options are available to pagination control view scripts: Property Type Description first integer First page number (typically 1). firstItemNumber integer Absolute number of the first item on this page. firstPageInRange integer First page in the range returned by the scrolling style. current integer Current page number. currentItemCount integer Number of items on this page. itemCountPerPage integer Maximum number of items available to each page. last integer Last page number. lastItemNumber integer Absolute number of the last item on this page. lastPageInRange integer Last page in the range returned by the scrolling style. next integer Next page number. pageCount integer Number of pages. pagesInRange array Array of pages returned by the scrolling style. previous integer Previous page number. totalItemCount integer Total number of items.","title":"Usage"},{"location":"v2/usage/#usage","text":"","title":"Usage"},{"location":"v2/usage/#paginating-data-collections","text":"In order to paginate items into pages, Laminas\\Paginator must have a generic way of accessing that data. For that reason, all data access takes place through data source adapters. Several adapters ship with laminas-paginator by default: Adapter Description ArrayAdapter Accepts a PHP array. DbSelect Accepts a Laminas\\Db\\Sql\\Select instance, plus either a Laminas\\Db\\Adapter\\Adapter or Laminas\\Db\\Sql\\Sql instance; paginates rows from a database. DbTableGateway Accepts a Laminas\\Db\\TableGateway\\AbstractTableGateway instance, and optionally additional arguments representing the WHERE, ORDER BY, GROUP BY, and/or HAVING clauases. Iterator Accepts any Iterator instance. NullFill Dummy paginator. To create a paginator instance, you must supply an adapter to the constructor: use Laminas\\Paginator\\Adapter; use Laminas\\Paginator\\Paginator; $paginator = new Paginator(new Adapter\\ArrayAdapter($array)); In the case of the NullFill adapter, in lieu of a data collection you must supply an item count to its constructor. Although the instance is technically usable in this state, in your controller action you'll need to tell the paginator what page number the user requested. This allows advancing through the paginated data. $paginator->setCurrentPageNumber($page); The simplest way to keep track of this value is through a URL parameter. The following is an example laminas-router route configuration: return [ 'routes' => [ 'paginator' => [ 'type' => 'segment', 'options' => [ 'route' => '/list/[page/:page]', 'defaults' => [ 'page' => 1, ], ], ], ], ]; With the above route (and using laminas-mvc controllers), you might set the current page number in your controller action like so: $paginator->setCurrentPageNumber($this->params()->fromRoute('page')); There are other options available; see the Configuration chapter for more on them. Finally, you'll need to assign the paginator instance to your view. If you're using laminas-mvc and laminas-view, you can assign the paginator object to your view model: $vm = new ViewModel(); $vm->setVariable('paginator', $paginator); return $vm;","title":"Paginating data collections"},{"location":"v2/usage/#the-dbselect-adapter","text":"","title":"The DbSelect adapter"},{"location":"v2/usage/#rendering-pages-with-view-scripts","text":"","title":"Rendering pages with view scripts"},{"location":"v2/application-integration/stand-alone/","text":"Stand-Alone The paginator can also be used stand-alone, outside of a Mezzio or laminas-mvc application. The example uses the following directory structure: example-app/ |-- public/ | `-- index.php |-- templates/ | `-- pagination-control.phtml `-- vendor `-- … Create and Configure Paginator Create a paginator and a related adapter , set the item count for one page and the current page number in public/index.php : // Create paginator $paginator = new Laminas\\Paginator\\Paginator( new Laminas\\Paginator\\Adapter\\ArrayAdapter($albums) ); // Configure paginator $paginator->setItemCountPerPage(4); $paginator->setCurrentPageNumber((int) ($_GET['page'] ?? 1)); Example Data $albums = [ [ 'artist' => 'David Bowie', 'title' => 'The Next Day (Deluxe Version)', ], [ 'artist' => 'Bastille', 'title' => 'Bad Blood', ], [ 'artist' => 'Bruno Mars', 'title' => 'Unorthodox Jukebox', ], [ 'artist' => 'Emeli Sandé', 'title' => 'Our Version of Events (Special Edition)', ], [ 'artist' => 'Bon Jovi', 'title' => 'What About Now (Deluxe Version)', ], [ 'artist' => 'Justin Timberlake', 'title' => 'The 20/20 Experience (Deluxe Version)', ], [ 'artist' => 'Bastille', 'title' => 'Bad Blood (The Extended Cut)', ], [ 'artist' => 'P!nk', 'title' => 'The Truth About Love', ], [ 'artist' => 'Sound City - Real to Reel', 'title' => 'Sound City - Real to Reel', ], [ 'artist' => 'Jake Bugg', 'title' => 'Jake Bugg', ], ]; Output Pure Data The data of each sub-array is returned by iteration over the paginator: foreach ($paginator as $item) { var_dump($item['artist']); // \"Bon Jovi\", \"Justin Timberlake\", … var_dump($item['title']); // \"What About Now (Deluxe Version)\", \"The 20/20 Experience (Deluxe Version)\", … } Retrieving the current status data of the paginator : var_dump($paginator->getPages()->previous); // 1 var_dump($paginator->getPages()->next); // 3 Usage with laminas-view Create View Script Create a view script in templates/pagination-control.phtml : <?php /** * @var Laminas\\View\\Renderer\\PhpRenderer $this * @var int $pageCount * @var int $previous * @var int $next * @var int $current * @var array<int, int> $pagesInRange */ ?> <?php if ($pageCount): ?> <nav aria-label=\"Page navigation example\"> <ul class=\"pagination\"> <!-- Previous page link --> <?php if (isset($previous)): ?> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=<?= $previous ?>\">Previous</a> </li> <?php else: ?> <li class=\"page-item disabled\"> <a class=\"page-link\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\">Previous</a> </li> <?php endif; ?> <!-- Numbered page links --> <?php foreach ($pagesInRange as $page): ?> <?php if ($page !== $current): ?> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=<?= $page ?>\"> <?= $page ?> </a> </li> <?php else: ?> <!-- Current page --> <li class=\"page-item active\" aria-current=\"page\"> <a class=\"page-link\" href=\"#\"><?= $page ?> <span class=\"sr-only\">(current)</span></a> </li> <?php endif; ?> <?php endforeach; ?> <!-- Next page link --> <?php if (isset($this->next)): ?> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=<?= $next ?>\">Next</a> </li> <?php else: ?> <li class=\"page-item disabled\"> <a class=\"page-link\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\">Next</a> </li> <?php endif; ?> </ul> </nav> <?php endif; ?> Setup Set a resolver for templates and set template for the related view helper in public/index.php : // Create template resolver $templateResolver = new Laminas\\View\\Resolver\\TemplatePathStack([ 'script_paths' => [__DIR__ . '/../templates'], ]); // Setup renderer /** @var Laminas\\View\\Renderer\\PhpRenderer $renderer */ $renderer = $paginator->getView(); $renderer->setResolver($templateResolver); // Set template for related view helper $renderer->plugin('paginationControl')->setDefaultViewPartial('pagination-control'); Render Output echo $paginator->render(); Output: <nav aria-label=\"Page navigation example\"> <ul class=\"pagination\"> <!-- Previous page link --> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=1\">Previous</a> </li> <!-- Numbered page links --> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=1\"> 1 </a> </li> <!-- Current page --> <li class=\"page-item active\" aria-current=\"page\"> <a class=\"page-link\" href=\"#\">2 <span class=\"sr-only\">(current)</span></a> </li> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=3\"> 3 </a> </li> <!-- Next page link --> <li class=\"page-item\"> <a class=\"page-link\" href=\"index.php?page=3\">Next</a> </li> </ul> </nav> Show full code example <?php require_once __DIR__ . '/../vendor/autoload.php'; $albums = [ [ 'artist' => 'David Bowie', 'title' => 'The Next Day (Deluxe Version)', ], [ 'artist' => 'Bastille', 'title' => 'Bad Blood', ], [ 'artist' => 'Bruno Mars', 'title' => 'Unorthodox Jukebox', ], [ 'artist' => 'Emeli Sandé', 'title' => 'Our Version of Events (Special Edition)', ], [ 'artist' => 'Bon Jovi', 'title' => 'What About Now (Deluxe Version)', ], [ 'artist' => 'Justin Timberlake', 'title' => 'The 20/20 Experience (Deluxe Version)', ], [ 'artist' => 'Bastille', 'title' => 'Bad Blood (The Extended Cut)', ], [ 'artist' => 'P!nk', 'title' => 'The Truth About Love', ], [ 'artist' => 'Sound City - Real to Reel', 'title' => 'Sound City - Real to Reel', ], [ 'artist' => 'Jake Bugg', 'title' => 'Jake Bugg', ], ]; // Create paginator $paginator = new Laminas\\Paginator\\Paginator( new Laminas\\Paginator\\Adapter\\ArrayAdapter($albums) ); $paginator->setItemCountPerPage(4); $paginator->setCurrentPageNumber((int) ($_GET['page'] ?? 1)); // Create template resolver $templateResolver = new Laminas\\View\\Resolver\\TemplatePathStack([ 'script_paths' => [__DIR__ . '/../templates'], ]); // Setup renderer /** @var Laminas\\View\\Renderer\\PhpRenderer $renderer */ $renderer = $paginator->getView(); $renderer->setResolver($templateResolver); // Set template for related view helper $renderer->plugin('paginationControl')->setDefaultViewPartial('pagination-control'); // Render output echo $paginator->render();","title":"Stand-Alone"},{"location":"v2/application-integration/stand-alone/#stand-alone","text":"The paginator can also be used stand-alone, outside of a Mezzio or laminas-mvc application. The example uses the following directory structure: example-app/ |-- public/ | `-- index.php |-- templates/ | `-- pagination-control.phtml `-- vendor `-- …","title":"Stand-Alone"},{"location":"v2/application-integration/stand-alone/#create-and-configure-paginator","text":"Create a paginator and a related adapter , set the item count for one page and the current page number in public/index.php : // Create paginator $paginator = new Laminas\\Paginator\\Paginator( new Laminas\\Paginator\\Adapter\\ArrayAdapter($albums) ); // Configure paginator $paginator->setItemCountPerPage(4); $paginator->setCurrentPageNumber((int) ($_GET['page'] ?? 1)); Example Data $albums = [ [ 'artist' => 'David Bowie', 'title' => 'The Next Day (Deluxe Version)', ], [ 'artist' => 'Bastille', 'title' => 'Bad Blood', ], [ 'artist' => 'Bruno Mars', 'title' => 'Unorthodox Jukebox', ], [ 'artist' => 'Emeli Sandé', 'title' => 'Our Version of Events (Special Edition)', ], [ 'artist' => 'Bon Jovi', 'title' => 'What About Now (Deluxe Version)', ], [ 'artist' => 'Justin Timberlake', 'title' => 'The 20/20 Experience (Deluxe Version)', ], [ 'artist' => 'Bastille', 'title' => 'Bad Blood (The Extended Cut)', ], [ 'artist' => 'P!nk', 'title' => 'The Truth About Love', ], [ 'artist' => 'Sound City - Real to Reel', 'title' => 'Sound City - Real to Reel', ], [ 'artist' => 'Jake Bugg', 'title' => 'Jake Bugg', ], ];","title":"Create and Configure Paginator"},{"location":"v2/application-integration/stand-alone/#output-pure-data","text":"The data of each sub-array is returned by iteration over the paginator: foreach ($paginator as $item) { var_dump($item['artist']); // \"Bon Jovi\", \"Justin Timberlake\", … var_dump($item['title']); // \"What About Now (Deluxe Version)\", \"The 20/20 Experience (Deluxe Version)\", … } Retrieving the current status data of the paginator : var_dump($paginator->getPages()->previous); // 1 var_dump($paginator->getPages()->next); // 3","title":"Output Pure Data"},{"location":"v2/application-integration/stand-alone/#usage-with-laminas-view","text":"","title":"Usage with laminas-view"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 9fb40ce0..6d4a3581 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,37 +2,30 @@ https://docs.laminas.dev/laminas-paginator/ - 2024-01-11 - daily + 2024-10-16 - https://docs.laminas.dev/laminas-paginator/advanced/ - 2024-01-11 - daily + https://docs.laminas.dev/laminas-paginator/v2/advanced/ + 2024-10-16 - https://docs.laminas.dev/laminas-paginator/configuration/ - 2024-01-11 - daily + https://docs.laminas.dev/laminas-paginator/v2/configuration/ + 2024-10-16 - https://docs.laminas.dev/laminas-paginator/installation/ - 2024-01-11 - daily + https://docs.laminas.dev/laminas-paginator/v2/installation/ + 2024-10-16 - https://docs.laminas.dev/laminas-paginator/intro/ - 2024-01-11 - daily + https://docs.laminas.dev/laminas-paginator/v2/intro/ + 2024-10-16 - https://docs.laminas.dev/laminas-paginator/usage/ - 2024-01-11 - daily + https://docs.laminas.dev/laminas-paginator/v2/usage/ + 2024-10-16 - https://docs.laminas.dev/laminas-paginator/application-integration/stand-alone/ - 2024-01-11 - daily + https://docs.laminas.dev/laminas-paginator/v2/application-integration/stand-alone/ + 2024-10-16 \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 40eec33993c13e932143f0166777553e0c368d5c..72e4db3e38483c09f249895df48d2e8737ad2c3d 100644 GIT binary patch literal 262 zcmV+h0r~zPiwFn+0uN^b|8r?{Wo=<_E_iKh0L@fOZp0uA-Oni^_COL@ zU;$;2h(VYnJ$^|hs=A*=>Wx3L-+RIq!}WU#&0;h8h$HJn%NmP18jo&dpC9l1gnrrHK@k9HeE)M`Va3S*)s z5n%ENB#d3;5%UDD`VzAosbhW4;M1& diff --git a/usage/index.html b/usage/index.html index 35036e78..6df9be2e 100644 --- a/usage/index.html +++ b/usage/index.html @@ -1,1091 +1,15 @@ - - + + - - - - - - - - - - - - - - Usage - laminas-paginator - Laminas Docs - - - + Redirecting... + + + + - - - - - - -
    -
    -
    - - -
    -

    - Components - - - laminas-paginator - -

    -
    - - - -
    -
    -
    - - -
    -
    -
    - - - - - - - - - - - - - - - - - - - - - - - -

    Usage

    -

    Paginating data collections

    -

    In order to paginate items into pages, Laminas\Paginator must have a generic way -of accessing that data. For that reason, all data access takes place through -data source adapters. Several adapters ship with laminas-paginator by default:

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    AdapterDescription
    ArrayAdapterAccepts a PHP array.
    DbSelectAccepts a Laminas\Db\Sql\Select instance, plus either a Laminas\Db\Adapter\Adapter or Laminas\Db\Sql\Sql instance; paginates rows from a database.
    DbTableGatewayAccepts a Laminas\Db\TableGateway\AbstractTableGateway instance, and optionally additional arguments representing the WHERE, ORDER BY, GROUP BY, and/or HAVING clauases.
    IteratorAccepts any Iterator instance.
    NullFillDummy paginator.
    -

    To create a paginator instance, you must supply an adapter to the constructor:

    -
    use Laminas\Paginator\Adapter;
    -use Laminas\Paginator\Paginator;
    -
    -$paginator = new Paginator(new Adapter\ArrayAdapter($array));
    -

    In the case of the NullFill adapter, in lieu of a data collection you must -supply an item count to its constructor.

    -

    Although the instance is technically usable in this state, in your controller -action you'll need to tell the paginator what page number the user requested. -This allows advancing through the paginated data.

    -
    $paginator->setCurrentPageNumber($page);
    -

    The simplest way to keep track of this value is through a URL parameter. The -following is an example laminas-router -route configuration:

    -
    return [
    -    'routes' => [
    -        'paginator' => [
    -            'type' => 'segment',
    -            'options' => [
    -                'route' => '/list/[page/:page]',
    -                'defaults' => [
    -                    'page' => 1,
    -                ],
    -            ],
    -        ],
    -    ],
    -];
    -

    With the above route (and using laminas-mvc -controllers), you might set the current page number in your controller action -like so:

    -
    $paginator->setCurrentPageNumber($this->params()->fromRoute('page'));
    -

    There are other options available; see the Configuration chapter -for more on them.

    -

    Finally, you'll need to assign the paginator instance to your view. If you're -using laminas-mvc and laminas-view, you can assign the paginator object to your view -model:

    -
    $vm = new ViewModel();
    -$vm->setVariable('paginator', $paginator);
    -return $vm;
    -

    The DbSelect adapter

    -
    -

    Deprecated

    -

    The adapter is deprecated since version 2.10.0. Please use the laminas/laminas-paginator-adapter-laminasdb package if you wish to use the laminas-db-based pagination adapters.

    -

    Installation Requirements

    -

    The DbSelect adapter depends on the laminas-db component, so be sure to have it -installed before getting started:

    -
    $ composer require laminas/laminas-db
    -

    Database optimizations

    -

    Instead of selecting every matching row of a given query, the DbSelect adapter -retrieves only the smallest amount of data necessary for displaying the -current page. Because of this, a second query is dynamically generated to -determine the total number of matching rows.

    -
    -

    Most adapters receive their datasets directly. However, the DbSelect adapter -requires a more detailed explanation regarding the retrieval and count of the -data from the database.

    -

    You do not have to retrieve data from the database prior to using the DbSelect -adapter; the adapter will do the retrieval for you, as well as provide a count -of total pages. If additional work has to be done on the database results which -cannot be expressed via the provided Laminas\Db\Sql\Select, object you must -extend the adapter and override the getItems() method.

    -

    Additionally this adapter does not fetch all records from the database in -order to count them. Instead, the adapter manipulates the original query to -produce a corresponding COUNT query, and uses the new query to get the number -of rows. While this approach requires an extra round-trip to the database, -doing so is stillmany times faster than fetching an entire result set and using -count(), especially with large collections of data.

    -

    The database adapter will try and build the most efficient query that will -execute on pretty much any modern database. However, depending on your database -or even your own schema setup, there might be more efficient ways to get a -rowcount.

    -

    There are two approaches for doing this. The first is to extend the DbSelect -adapter and override the count() method:

    -
    class MyDbSelect extends DbSelect
    -{
    -    public function count()
    -    {
    -        if ($this->rowCount) {
    -            return $this->rowCount;
    -        }
    -
    -        $select = new Select();
    -        $select
    -          ->from('item_counts')
    -          ->columns(['c'=>'post_count']);
    -
    -        $statement = $this->sql->prepareStatementForSqlObject($select);
    -        $result    = $statement->execute();
    -        $row       = $result->current();
    -        $this->rowCount = $row['c'];
    -
    -        return $this->rowCount;
    -    }
    -}
    -
    -$adapter = new MyDbSelect($query, $adapter);
    -

    Alternately, you can pass an additional Laminas\Db\Sql\Select object as the -fourth constructor argument to the DbSelect adapter to implement a custom -count query.

    -

    For example, if you keep track of the count of blog posts in a separate table, -you could achieve a faster count query with the following setup:

    -
    use Laminas\Db\Sql\Select;
    -use Laminas\Paginator\Adapter\DbSelect;
    -use Laminas\Paginator\Paginator;
    -
    -$countQuery = new Select();
    -$countQuery
    -    ->from('item_counts')
    -    ->columns([ DbSelect::ROW_COUNT_COLUMN_NAME => 'post_count' ]);
    -
    -$adapter = new DbSelect($query, $dbAdapter, null, $countQuery);
    -$paginator = new Paginator($adapter);
    -

    Alternatively, the same can be achieved using the provided factory:

    -
    use Laminas\Paginator\Adapter\DbSelect;
    -use Laminas\Paginator\Factory as PaginatorFactory;
    -
    -$countQuery = new Select();
    -$countQuery
    -    ->from('item_counts')
    -    ->columns([ DbSelect::ROW_COUNT_COLUMN_NAME => 'post_count' ]);
    -
    -$paginator = PaginatorFactory::factory(
    -    [
    -        $query,
    -        $dbAdapter,
    -        null,
    -        $countQuery,
    -    ],
    -    DbSelect::class
    -);
    -

    This approach will probably not give you a huge performance gain on small -collections and/or simple select queries. However, with complex queries and -large collections, a similar approach could give you a significant performance -boost.

    -

    The DbSelect adapter also supports returning of fetched records using the -ResultSet subcomponent of laminas-db. -You can override the concrete ResultSet implementation by passing an object -implementing Laminas\Db\ResultSet\ResultSetInterface as the third constructor -argument to the DbSelect adapter:

    -
    use Laminas\Db\ResultSet\HydratingResultSet;
    -use Laminas\Paginator\Adapter\DbSelect;
    -use Laminas\Paginator\Paginator;
    -
    -// $objectPrototype is an instance of our custom entity
    -// $hydrator is a custom hydrator for our entity
    -// (implementing Laminas\Hydrator\HydratorInterface)
    -$resultSet = new HydratingResultSet($hydrator, $objectPrototype);
    -
    -$adapter = new DbSelect($query, $dbAdapter, $resultSet)
    -$paginator = new Laminas\Paginator\Paginator($adapter);
    -

    Now when we iterate over $paginator we will get instances of our custom entity -instead of associative arrays.

    -

    Rendering pages with view scripts

    -
    -

    Installation Requirements

    -

    The rendering with view scripts depends on the laminas-view component, so be sure -to have it installed before getting started:

    -
    $ composer require laminas/laminas-view
    -
    -

    The view script is used to render the page items (if you're using -laminas-paginator to do so) and display the pagination control.

    -

    Because Laminas\Paginator\Paginator implements the SPL interface -IteratorAggregate, you can loop over an -instance using foreach:

    -
    <html>
    -<body>
    -<h1>Example</h1>
    -<?php if (count($this->paginator)): ?>
    -<ul>
    -<?php foreach ($this->paginator as $item): ?>
    -  <li><?= $item; ?></li>
    -<?php endforeach; ?>
    -</ul>
    -<?php endif; ?>
    -
    -<?= $this->paginationControl(
    -    $this->paginator,
    -    'Sliding',
    -    'my_pagination_control',
    -    ['route' => 'application/paginator']
    -) ?>
    -</body>
    -</html>
    -

    Notice the view helper call near the end. PaginationControl accepts up to four -parameters: the paginator instance, a scrolling style, a view script name, and -an array of additional parameters.

    -

    The second and third parameters are very important. Whereas the view script name -is used to determine how the pagination control should look, the scrolling -style is used to control how it should behave. Say the view script is in the -style of a search pagination control, like the one below:

    -

    Pagination controls

    -

    What happens when the user clicks the "next" link a few times? Well, any number of things could -happen:

    -
      -
    • The current page number could stay in the middle as you click through (as it - does on Yahoo!)
    • -
    • It could advance to the end of the page range and then appear again on the - left when the user clicks "next" one more time.
    • -
    • The page numbers might even expand and contract as the user advances (or - "scrolls") through them (as they do on Google).
    • -
    -

    There are four scrolling styles packaged with Laminas:

    -
    - - - - - - - - - - - - - - - - - - - - - - - - -
    Scrolling styleDescription
    AllReturns every page. This is useful for dropdown menu pagination controls with relatively few pages. In these cases, you want all pages available to the user at once.
    ElasticA Google-like scrolling style that expands and contracts as a user scrolls through the pages.
    JumpingAs users scroll through, the page number advances to the end of a given range, then starts again at the beginning of the new range.
    SlidingA Yahoo!-like scrolling style that positions the current page number in the center of the page range, or as close as possible. This is the default style.
    -

    The fourth and final parameter is reserved for an optional associative array of -variables that you want available in your view (available via $this). For -instance, these values could include extra URL parameters for pagination links.

    -

    By setting the default view script name, default scrolling style, and view -instance, you can eliminate the calls to PaginationControl completely:

    -
    use Laminas\Paginator\Paginator;
    -use Laminas\View\Helper\PaginationControl;
    -
    -Paginator::setDefaultScrollingStyle('Sliding');
    -PaginationControl::setDefaultViewPartial('my_pagination_control');
    -

    When all of these values are set, you can render the pagination control inside -your view script by echoing the paginator instance:

    -
    <?= $this->paginator ?>
    -
    -

    Using other template engines

    -

    Of course, it's possible to use laminas-paginator with other template engines. -For example, with Smarty you might do the following:

    -
    $smarty-assign('pages', $paginator->getPages());
    -

    You could then access paginator values from a template like so:

    -
    {$pages.pageCount}
    -
    -

    Example pagination controls

    -

    The following example pagination controls will help you get started with -laminas-view:

    -

    Search pagination:

    -
    <!--
    -See http://developer.yahoo.com/ypatterns/pattern.php?pattern=searchpagination
    --->
    -
    -<?php if ($this->pageCount): ?>
    -<div class="paginationControl">
    -<!-- Previous page link -->
    -<?php if (isset($this->previous)): ?>
    -  <a href="<?= $this->url($this->route, ['page' => $this->previous]); ?>">
    -    &lt; Previous
    -  </a> |
    -<?php else: ?>
    -  <span class="disabled">&lt; Previous</span> |
    -<?php endif; ?>
    -
    -<!-- Numbered page links -->
    -<?php foreach ($this->pagesInRange as $page): ?>
    -  <?php if ($page != $this->current): ?>
    -    <a href="<?= $this->url($this->route, ['page' => $page]); ?>">
    -        <?= $page; ?>
    -    </a> |
    -  <?php else: ?>
    -    <?= $page; ?> |
    -  <?php endif; ?>
    -<?php endforeach; ?>
    -
    -<!-- Next page link -->
    -<?php if (isset($this->next)): ?>
    -  <a href="<?= $this->url($this->route, ['page' => $this->next]); ?>">
    -    Next &gt;
    -  </a>
    -<?php else: ?>
    -  <span class="disabled">Next &gt;</span>
    -<?php endif; ?>
    -</div>
    -<?php endif; ?>
    -

    Item pagination:

    -
    <!--
    -See http://developer.yahoo.com/ypatterns/pattern.php?pattern=itempagination
    --->
    -
    -<?php if ($this->pageCount): ?>
    -<div class="paginationControl">
    -<?= $this->firstItemNumber; ?> - <?= $this->lastItemNumber; ?>
    -of <?= $this->totalItemCount; ?>
    -
    -<!-- First page link -->
    -<?php if (isset($this->previous)): ?>
    -  <a href="<?= $this->url($this->route, ['page' => $this->first]); ?>">
    -    First
    -  </a> |
    -<?php else: ?>
    -  <span class="disabled">First</span> |
    -<?php endif; ?>
    -
    -<!-- Previous page link -->
    -<?php if (isset($this->previous)): ?>
    -  <a href="<?= $this->url($this->route, ['page' => $this->previous]); ?>">
    -    &lt; Previous
    -  </a> |
    -<?php else: ?>
    -  <span class="disabled">&lt; Previous</span> |
    -<?php endif; ?>
    -
    -<!-- Next page link -->
    -<?php if (isset($this->next)): ?>
    -  <a href="<?= $this->url($this->route, ['page' => $this->next]); ?>">
    -    Next &gt;
    -  </a> |
    -<?php else: ?>
    -  <span class="disabled">Next &gt;</span> |
    -<?php endif; ?>
    -
    -<!-- Last page link -->
    -<?php if (isset($this->next)): ?>
    -  <a href="<?= $this->url($this->route, ['page' => $this->last]); ?>">
    -    Last
    -  </a>
    -<?php else: ?>
    -  <span class="disabled">Last</span>
    -<?php endif; ?>
    -
    -</div>
    -<?php endif; ?>
    -

    Dropdown pagination:

    -
    <?php if ($this->pageCount): ?>
    -<select id="paginationControl" size="1">
    -<?php foreach ($this->pagesInRange as $page): ?>
    -  <?php $selected = ($page == $this->current) ? ' selected="selected"' : ''; ?>
    -  <option value="<?= $this->url($this->route, ['page' => $page]);?>"<?= $selected ?>>
    -    <?= $page; ?>
    -  </option>
    -<?php endforeach; ?>
    -</select>
    -<?php endif; ?>
    -
    -<script type="text/javascript"
    -     src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js">
    -</script>
    -<script type="text/javascript">
    -$('paginationControl').observe('change', function() {
    -    window.location = this.options[this.selectedIndex].value;
    -})
    -</script>
    -

    Listing of properties

    -

    The following options are available to pagination control view scripts:

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    PropertyTypeDescription
    firstintegerFirst page number (typically 1).
    firstItemNumberintegerAbsolute number of the first item on this page.
    firstPageInRangeintegerFirst page in the range returned by the scrolling style.
    currentintegerCurrent page number.
    currentItemCountintegerNumber of items on this page.
    itemCountPerPageintegerMaximum number of items available to each page.
    lastintegerLast page number.
    lastItemNumberintegerAbsolute number of the last item on this page.
    lastPageInRangeintegerLast page in the range returned by the scrolling style.
    nextintegerNext page number.
    pageCountintegerNumber of pages.
    pagesInRangearrayArray of pages returned by the scrolling style.
    previousintegerPrevious page number.
    totalItemCountintegerTotal number of items.
    - - - - - - - - - -
    - -
    -
    - - - - - - - - - - - - + +Redirecting... - - diff --git a/v2/advanced/index.html b/v2/advanced/index.html new file mode 100644 index 00000000..ecbcb8a6 --- /dev/null +++ b/v2/advanced/index.html @@ -0,0 +1,715 @@ + + + + + + + + + + + + + + + + + + + + + Advanced Usage - laminas-paginator - Laminas Docs + + + + + + + + + + +
    +
    +
    + + +
    +

    + Components + + + laminas-paginator + +

    +
    + + + +
    +
    +
    + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    Advanced usage

    +

    Using the Paginator Adapter Plugin Manager

    +

    laminas-paginator ships with a plugin manager for adapters, Laminas\Paginator\AdapterPluginManager. +The plugin manager can be used to retrieve adapters. +Since most adapters require constructor arguments, they may be passed as the second argument to the get() method in the same order they appear in the constructor.

    +

    Examples

    +
    use Laminas\Paginator\Adapter;
    +use Laminas\Paginator\AdapterPluginManager;
    +
    +$pluginManager = new AdapterPluginManager();
    +
    +// Get an array adapter for an array of items
    +$arrayAdapter = $pluginManager->get(Adapter\ArrayAdapter::class, [$arrayOfItems]);
    +
    +// Get a DbSelect adapter based on a Laminas\Db\Sql\Select instance and a DB adapter:
    +$dbSelectAdapter = $pluginManager->get(Adapter\DbSelect::class, [
    +    $select,
    +    $dbAdapter
    +]);
    +
    +// Get a DbTableGateway adapter based on a Laminas\Db\TableGateway\TableGateway instance:
    +$dbTDGAdapter = $pluginManager->get(Adapter\DbTableGateway::class, [$tableGateway]);
    +
    +// Get an Iterator adapter based on an iterator:
    +$iteratorAdapter = $pluginManager->get(Adapter\Iterator::class, [$iterator]);
    +
    +

    Note: the laminas-db-based adapters are deprecated since version 2.10.0.

    +
    +

    Custom data source adapters

    +

    At some point you may run across a data type that is not covered by the packaged +adapters. In this case, you will need to write your own.

    +

    To do so, you must implement Laminas\Paginator\Adapter\AdapterInterface. There +are two methods required to do this:

    +
      +
    • count() : int
    • +
    • getItems(int $offset, int $itemCountPerPage) | array
    • +
    +

    Additionally, you'll typically implement a constructor that takes your data +source as a parameter.

    +

    If you've ever used the SPL interface Countable, +you're familiar with count(). As used with laminas-paginator, this is the total +number of items in the data collection; Laminas\Paginator\Paginator::countAllItems +proxies to this method.

    +

    When retrieving items for the current page, Laminas\Paginator\Paginator calls on +your adapter's getItems() method, providing it with an offset and the number +of items to display per page; your job is to return the appropriate slice of +data. For an array, that would be:

    +
    return array_slice($this->array, $offset, $itemCountPerPage);
    +

    Take a look at the packaged adapters for ideas of how you might go about +implementing your own.

    +

    Registering Your Adapter with the Plugin Manager

    +
    +

    Available since version 2.10.0.

    +
    +

    If you want to register your adapter with the Laminas\Pagiantor\AdapterPluginManager, you can do so via configuration. +The "paginators" configuration key can contain standard laminas-servicemanager-style configuration.

    +

    One possibility is to add it to the config/autoload/global.php file:

    +
    return [
    +    // ...
    +    'paginators' => [
    +        'factories' => [
    +            YourCustomPaginationAdapter::class => YourCustomPaginationAdapterFactory::class,
    +        ],
    +    ],
    +];
    +

    This allows you to retrieve the AdapterPluginManager in a factory, and then pull your adapter from it. +As an example, consider the following factory:

    +
    use Laminas\Paginator\AdapterPluginManager;
    +use Laminas\Paginator\Paginator;
    +use Psr\Container\ContainerInterface;
    +
    +class SomeServiceFactory
    +{
    +    public function __invoke(ContainerInterface $container)
    +    {
    +        $paginators = $container->get(AdapterPluginManager::class);
    +        $paginator  = new Paginator($paginators->get(YourCustomPaginatorAdapter::class));
    +        // ...
    +    }
    +}
    +

    Custom scrolling styles

    +

    Creating your own scrolling style requires that you implement +Laminas\Paginator\ScrollingStyle\ScrollingStyleInterface, which defines a single +method:

    +
    getPages(Paginator $paginator, int $pageRange = null) : array
    +

    This method should calculate a lower and upper bound for page numbers within the +range of so-called "local" pages (that is, pages that are nearby the current +page).

    +

    Unless it extends another scrolling style (see +Laminas\Paginator\ScrollingStyle\Elastic for an example), your custom scrolling +style will inevitably end with something similar to the following line of code:

    +
    return $paginator->getPagesInRange($lowerBound, $upperBound);
    +

    There's nothing special about this call; it's merely a convenience method to +check the validity of the lower and upper bound and return an array with the range +to the paginator.

    +

    When you're ready to use your new scrolling style, you'll need to notif +Laminas\Paginator\Paginator:

    +
    use My\Paginator\ScrollingStyle;
    +use Laminas\Paginator\Paginator;
    +use Laminas\ServiceManager\Factory\InvokableFactory;
    +
    +$manager = Paginator::getScrollingStyleManager();
    +$manager->setAlias('my-style', ScrollingStyle::class);
    +$manager->setFactory(ScrollingStyle::class, InvokableFactory::class);
    +

    Caching features

    +
    +

    Installation Requirements

    +

    The caching features depends on the laminas-cache component, so be sure to have +it installed before getting started:

    +
    $ composer require laminas/laminas-cache
    +
    +

    Laminas\Paginator\Paginator can be told to cache the data it has already used, +preventing the adapter from fetching on next request. To tell +paginator to automatically cache the adapter's data, pass a pre-configured +laminas-cache adapter +to the static setCache() method:

    +
    use Laminas\Cache\StorageFactory;
    +use Laminas\Paginator\Paginator;
    +
    +$cache = StorageFactory::adapterFactory('filesystem', [
    +    'cache_dir' => '/tmp',
    +    'ttl'       => 3600,
    +    'plugins'   => [ 'serializer' ],
    +]);
    +Paginator::setCache($cache);
    +

    As long as the Paginator class has been seeded with a cache storage object, +the data any instance generates will be cached. If you want to disable caching, call +setCacheEnabled() with a boolean false on a concrete instance:

    +
    use Laminas\Paginator\Paginator;
    +
    +// $cache is a Laminas\Cache\Storage\StorageInterface instance
    +Paginator::setCache($cache);
    +
    +// ... later on the script:
    +$paginator->setCacheEnabled(false);
    +// cache is now disabled for this instance.
    +

    When a cache is set, data are automatically stored in it and pulled out from it. +It then can be useful to empty the cache manually. You can get this done by +calling clearPageItemCache($pageNumber). If you don't pass any parameter, the +whole cache will be empty. You can optionally pass a parameter representing the +page number to empty in the cache:

    +
    use Laminas\Paginator\Paginator;
    +
    +// $cache is a Laminas\Cache\Storage\StorageInterface instance
    +Paginator::setCache($cache);
    +
    +// $paginator is a fully configured Paginator instance:
    +$items = $paginator->getCurrentItems();
    +
    +$page3Items = $paginator->getItemsByPage(3);
    +// page 3 is now in cache
    +
    +// clear the cache of the results for page 3
    +$paginator->clearPageItemCache(3);
    +
    +// clear all the cache data
    +$paginator->clearPageItemCache();
    +

    Changing the item count per page will empty the whole cache as it would have +become invalid:

    +
    use Laminas\Paginator\Paginator;
    +
    +// $cache is a Laminas\Cache\Storage\StorageInterface instance
    +Paginator::setCache($cache);
    +
    +// Fetch some items from an instance:
    +$items = $paginator->getCurrentItems();
    +
    +// Changing item count flushes the cache:
    +$paginator->setItemCountPerPage(2);
    +

    It is also possible to see the data in cache and ask for it directly. +getPageItemCache() can be used for that:

    +
    use Laminas\Paginator\Paginator;
    +
    +// $cache is a Laminas\Cache\Storage\StorageInterface instance
    +Paginator::setCache($cache);
    +
    +// Set the item count:
    +$paginator->setItemCountPerPage(3);
    +
    +// Fetch some items:
    +$items = $paginator->getCurrentItems();
    +$otherItems = $paginator->getItemsPerPage(4);
    +
    +// See the cached items as a two-dimensional array:
    +var_dump($paginator->getPageItemCache());
    + + + + + + + + + +
    + +
    +
    + + + + + + + + + + + + + + + + diff --git a/v2/application-integration/stand-alone/index.html b/v2/application-integration/stand-alone/index.html new file mode 100644 index 00000000..2db3efa0 --- /dev/null +++ b/v2/application-integration/stand-alone/index.html @@ -0,0 +1,790 @@ + + + + + + + + + + + + + + + + + + + + + Stand-Alone - laminas-paginator - Laminas Docs + + + + + + + + + + +
    +
    +
    + + +
    +

    + Components + + + laminas-paginator + +

    +
    + + + +
    +
    +
    + + +
    +
    +
    + + + + + + + +
    +
    On this page
    + +
    + + + + + + + + + + + + + + +

    Application Integration

    + + +

    Stand-Alone

    +

    The paginator can also be used stand-alone, outside of a Mezzio or laminas-mvc +application.

    +

    The example uses the following directory structure:

    +
    example-app/
    +|-- public/
    +|   `-- index.php
    +|-- templates/
    +|   `-- pagination-control.phtml
    +`-- vendor
    +    `-- …
    +

    Create and Configure Paginator

    +

    Create a paginator and a related adapter, +set the item count for one page and the current page number in public/index.php:

    +
    // Create paginator
    +$paginator = new Laminas\Paginator\Paginator(
    +    new Laminas\Paginator\Adapter\ArrayAdapter($albums)
    +);
    +
    +// Configure paginator
    +$paginator->setItemCountPerPage(4);
    +$paginator->setCurrentPageNumber((int) ($_GET['page'] ?? 1));
    + +
    Example Data + +
    $albums = [
    +    [
    +        'artist' => 'David Bowie',
    +        'title'  => 'The Next Day (Deluxe Version)',
    +    ],
    +    [
    +        'artist' => 'Bastille',
    +        'title'  => 'Bad Blood',
    +    ],
    +    [
    +        'artist' => 'Bruno Mars',
    +        'title'  => 'Unorthodox Jukebox',
    +    ],
    +    [
    +        'artist' => 'Emeli Sandé',
    +        'title'  => 'Our Version of Events (Special Edition)',
    +    ],
    +    [
    +        'artist' => 'Bon Jovi',
    +        'title'  => 'What About Now (Deluxe Version)',
    +    ],
    +    [
    +        'artist' => 'Justin Timberlake',
    +        'title'  => 'The 20/20 Experience (Deluxe Version)',
    +    ],
    +    [
    +        'artist' => 'Bastille',
    +        'title'  => 'Bad Blood (The Extended Cut)',
    +    ],
    +    [
    +        'artist' => 'P!nk',
    +        'title'  => 'The Truth About Love',
    +    ],
    +    [
    +        'artist' => 'Sound City - Real to Reel',
    +        'title'  => 'Sound City - Real to Reel',
    +    ],
    +    [
    +        'artist' => 'Jake Bugg',
    +        'title'  => 'Jake Bugg',
    +    ],
    +];
    + + +
    + +

    Output Pure Data

    +

    The data of each sub-array is returned by iteration over the paginator:

    +
    foreach ($paginator as $item) {
    +    var_dump($item['artist']); // "Bon Jovi", "Justin Timberlake", …
    +    var_dump($item['title']); // "What About Now (Deluxe Version)", "The 20/20 Experience (Deluxe Version)", …
    +}
    +

    Retrieving the current status data of the paginator:

    +
    var_dump($paginator->getPages()->previous); // 1
    +var_dump($paginator->getPages()->next); // 3
    +

    Usage with laminas-view

    +

    Create View Script

    +

    Create a view script in +templates/pagination-control.phtml:

    +
    <?php
    +/**
    + * @var Laminas\View\Renderer\PhpRenderer $this
    + * @var int                               $pageCount
    + * @var int                               $previous
    + * @var int                               $next
    + * @var int                               $current
    + * @var array<int, int>                   $pagesInRange
    + */
    +?>
    +
    +<?php if ($pageCount): ?>
    +    <nav aria-label="Page navigation example">
    +        <ul class="pagination">
    +        <!-- Previous page link -->
    +        <?php if (isset($previous)): ?>
    +            <li class="page-item">
    +                <a class="page-link" href="index.php?page=<?= $previous ?>">Previous</a>
    +            </li>
    +        <?php else: ?>
    +            <li class="page-item disabled">
    +                <a class="page-link" href="#" tabindex="-1" aria-disabled="true">Previous</a>
    +            </li>
    +        <?php endif; ?>
    +
    +        <!-- Numbered page links -->
    +        <?php foreach ($pagesInRange as $page): ?>
    +            <?php if ($page !== $current): ?>
    +                <li class="page-item">
    +                    <a class="page-link" href="index.php?page=<?= $page ?>">
    +                        <?= $page ?>
    +                    </a>
    +                </li>
    +            <?php else: ?>
    +                <!-- Current page -->
    +                <li class="page-item active" aria-current="page">
    +                    <a class="page-link" href="#"><?= $page ?> <span class="sr-only">(current)</span></a>
    +                </li>
    +            <?php endif; ?>
    +        <?php endforeach; ?>
    +
    +        <!-- Next page link -->
    +        <?php if (isset($this->next)): ?>
    +            <li class="page-item">
    +                <a class="page-link" href="index.php?page=<?= $next ?>">Next</a>
    +            </li>
    +        <?php else: ?>
    +            <li class="page-item disabled">
    +                <a class="page-link" href="#" tabindex="-1" aria-disabled="true">Next</a>
    +            </li>
    +        <?php endif; ?>
    +        </ul>
    +    </nav>
    +<?php endif; ?>
    +

    Setup

    +

    Set a resolver for templates +and set template for the related view helper +in public/index.php:

    +
    // Create template resolver
    +$templateResolver = new Laminas\View\Resolver\TemplatePathStack([
    +    'script_paths' => [__DIR__ . '/../templates'],
    +]);
    +
    +// Setup renderer
    +/** @var Laminas\View\Renderer\PhpRenderer $renderer */
    +$renderer = $paginator->getView();
    +$renderer->setResolver($templateResolver);
    +
    +// Set template for related view helper
    +$renderer->plugin('paginationControl')->setDefaultViewPartial('pagination-control');
    +

    Render Output

    +
    echo $paginator->render();
    +

    Output:

    +
    <nav aria-label="Page navigation example">
    +    <ul class="pagination">
    +        <!-- Previous page link -->
    +        <li class="page-item">
    +            <a class="page-link" href="index.php?page=1">Previous</a>
    +        </li>
    +
    +        <!-- Numbered page links -->
    +        <li class="page-item">
    +            <a class="page-link" href="index.php?page=1">
    +                1
    +            </a>
    +        </li>
    +        <!-- Current page -->
    +        <li class="page-item active" aria-current="page">
    +            <a class="page-link" href="#">2 <span class="sr-only">(current)</span></a>
    +        </li>
    +        <li class="page-item">
    +            <a class="page-link" href="index.php?page=3">
    +                3
    +            </a>
    +        </li>
    +
    +        <!-- Next page link -->
    +        <li class="page-item">
    +            <a class="page-link" href="index.php?page=3">Next</a>
    +        </li>
    +    </ul>
    +</nav>
    + +
    Show full code example + +
    <?php
    +
    +require_once __DIR__ . '/../vendor/autoload.php';
    +
    +$albums = [
    +    [
    +        'artist' => 'David Bowie',
    +        'title'  => 'The Next Day (Deluxe Version)',
    +    ],
    +    [
    +        'artist' => 'Bastille',
    +        'title'  => 'Bad Blood',
    +    ],
    +    [
    +        'artist' => 'Bruno Mars',
    +        'title'  => 'Unorthodox Jukebox',
    +    ],
    +    [
    +        'artist' => 'Emeli Sandé',
    +        'title'  => 'Our Version of Events (Special Edition)',
    +    ],
    +    [
    +        'artist' => 'Bon Jovi',
    +        'title'  => 'What About Now (Deluxe Version)',
    +    ],
    +    [
    +        'artist' => 'Justin Timberlake',
    +        'title'  => 'The 20/20 Experience (Deluxe Version)',
    +    ],
    +    [
    +        'artist' => 'Bastille',
    +        'title'  => 'Bad Blood (The Extended Cut)',
    +    ],
    +    [
    +        'artist' => 'P!nk',
    +        'title'  => 'The Truth About Love',
    +    ],
    +    [
    +        'artist' => 'Sound City - Real to Reel',
    +        'title'  => 'Sound City - Real to Reel',
    +    ],
    +    [
    +        'artist' => 'Jake Bugg',
    +        'title'  => 'Jake Bugg',
    +    ],
    +];
    +
    +// Create paginator
    +$paginator = new Laminas\Paginator\Paginator(
    +    new Laminas\Paginator\Adapter\ArrayAdapter($albums)
    +);
    +$paginator->setItemCountPerPage(4);
    +$paginator->setCurrentPageNumber((int) ($_GET['page'] ?? 1));
    +
    +// Create template resolver
    +$templateResolver = new Laminas\View\Resolver\TemplatePathStack([
    +    'script_paths' => [__DIR__ . '/../templates'],
    +]);
    +
    +// Setup renderer
    +/** @var Laminas\View\Renderer\PhpRenderer $renderer */
    +$renderer = $paginator->getView();
    +$renderer->setResolver($templateResolver);
    +
    +// Set template for related view helper
    +$renderer->plugin('paginationControl')->setDefaultViewPartial('pagination-control');
    +
    +// Render output
    +echo $paginator->render();
    + + +
    + + + + + + + + + +
    + +
    +
    + + + + + + + + + + + + + + + + diff --git a/v2/configuration/index.html b/v2/configuration/index.html new file mode 100644 index 00000000..25e84701 --- /dev/null +++ b/v2/configuration/index.html @@ -0,0 +1,535 @@ + + + + + + + + + + + + + + + + + + + + + Configuration - laminas-paginator - Laminas Docs + + + + + + + + + + +
    +
    +
    + + +
    +

    + Components + + + laminas-paginator + +

    +
    + + + +
    +
    +
    + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + +

    Configuration

    +

    Laminas\Paginator has several configuration methods that can be called:

    +
    + + + + + + + + + + + + + + + + + + + + + + + + +
    Method signatureDescription
    setCurrentPageNumber(int $page) : voidSets the current page number (default 1).
    setItemCountPerPage(int $count) : voidSets the maximum number of items to display on a page (default 10).
    setPageRange(int $range) : voidSets the number of items to display in the pagination control (default 10). Note: Most of the time this number will be adhered to exactly, but scrolling styles do have the option of only using it as a guideline or starting value (e.g., Elastic).
    setView(Laminas\View\Renderer\RendererInterface $view) : voidSets the view instance, for rendering convenience.
    + + + + + + + + + +
    + +
    +
    + + + + + + + + + + + + + + + + diff --git a/images/usage-rendering-control.png b/v2/images/usage-rendering-control.png similarity index 100% rename from images/usage-rendering-control.png rename to v2/images/usage-rendering-control.png diff --git a/v2/installation/index.html b/v2/installation/index.html new file mode 100644 index 00000000..a03cf166 --- /dev/null +++ b/v2/installation/index.html @@ -0,0 +1,636 @@ + + + + + + + + + + + + + + + + + + + + + Installation - laminas-paginator - Laminas Docs + + + + + + + + + + +
    +
    +
    + + +
    +

    + Components + + + laminas-paginator + +

    +
    + + + +
    +
    +
    + + +
    +
    +
    + + + + + + + + + + + + +

    Installation

    + + + +

    Standard Installation

    +

    To install the library use Composer:

    +
    $ composer require laminas/laminas-paginator
    + + + +

    + Installation for a + Mezzio + or + laminas-mvc + Application +

    + +

    Installation and Automated Configuration

    +

    + The laminas-component-installer + is the recommended installation method when using in + a Mezzio-based + or + a laminas-mvc-based application. + It will automatically inject + the config-provider + or + the module + in the configuration during the installation process. +

    + +
    +

    Installation Requirements

    +

    + The following descriptions depends on the laminas-component-installer component, + so be sure to have it installed before getting started. +

    + +

    Global Installation

    +

    + With a global installation + of laminas-component-installer it can be used for all projects without a + reinstallation. +

    +
    $ composer global require laminas/laminas-component-installer
    +

    As Development Dependency

    +
    $ composer require --dev laminas/laminas-component-installer
    +
    + +

    Install laminas-paginator and Inject Configuration

    +

    To install the library use Composer:

    +
    $ composer require laminas/laminas-paginator
    +

    + This will install an initial set of dependencies and it will also prompt to + inject the component configuration. +

    +
      + +
    • For a Mezzio application, choose config/config.php.
    • + + +
    • For a laminas-mvc application, choose either modules.config.php or application.config.php.
    • + +
    +

    + If additional dependencies are to be installed, the option for other packages + can be remembered. +

    + +
    Installation and Manual Configuration +

    + If the installer is not used, the manual configuration is needed to add the + component to the application. +

    + +

    Install laminas-paginator

    +

    To install the library use Composer:

    +
    $ composer require laminas/laminas-paginator
    + + +

    Manual Configuration for a Mezzio-based Application

    +

    + Add the configuration provider of laminas-paginator to the configuration file, + e.g. config/config.php: +

    + +
    
    +$aggregator = new Laminas\ConfigAggregator\ConfigAggregator([
    +    // …
    +    Mezzio\ConfigProvider::class,
    +    Mezzio\Router\ConfigProvider::class,
    +    Laminas\Paginator\ConfigProvider, // Add this line
    +    // …
    +]);
    +
    + + + +

    Manual Configuration for a laminas-mvc-based Application

    +

    + Add laminas-paginator as component at the top of the configuration file for + modules, e.g. config/modules.config.php: +

    + +
    
    +return [
    +    'Laminas\Paginator\Module', // Add this line
    +    'Laminas\Router',
    +    'Laminas\Session',
    +    'Laminas\Validator',
    +    'Application',
    +];
    +
    + +
    + + + + + + + + + + + + +
    + +
    +
    + + + + + + + + + + + + + + + + diff --git a/v2/intro/index.html b/v2/intro/index.html new file mode 100644 index 00000000..f485ea47 --- /dev/null +++ b/v2/intro/index.html @@ -0,0 +1,519 @@ + + + + + + + + + + + + + + + + + + + + + Introduction - laminas-paginator - Laminas Docs + + + + + + + + + + +
    +
    +
    + + +
    +

    + Components + + + laminas-paginator + +

    +
    + + + +
    +
    +
    + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + +

    Introduction

    +

    laminas-paginator is a flexible component for paginating collections of data and +presenting that data to users.

    +

    The primary design goals of laminas-paginator are as follows:

    +
      +
    • Paginate arbitrary data, not just relational databases.
    • +
    • Fetch only the results that need to be displayed.
    • +
    • Do not force users to adhere to only one way of displaying data or rendering + pagination controls.
    • +
    • Loosely couple to other Laminas components so that users who wish to + use it independently of laminas-view, laminas-cache, etc. can do so.
    • +
    + + + + + + + + + +
    + +
    +
    + + + + + + + + + + + + + + + + diff --git a/v2/usage/index.html b/v2/usage/index.html new file mode 100644 index 00000000..3a3f5051 --- /dev/null +++ b/v2/usage/index.html @@ -0,0 +1,1001 @@ + + + + + + + + + + + + + + + + + + + + + Usage - laminas-paginator - Laminas Docs + + + + + + + + + + +
    +
    +
    + + +
    +

    + Components + + + laminas-paginator + +

    +
    + + + +
    +
    +
    + + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + +

    Usage

    +

    Paginating data collections

    +

    In order to paginate items into pages, Laminas\Paginator must have a generic way +of accessing that data. For that reason, all data access takes place through +data source adapters. Several adapters ship with laminas-paginator by default:

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AdapterDescription
    ArrayAdapterAccepts a PHP array.
    DbSelectAccepts a Laminas\Db\Sql\Select instance, plus either a Laminas\Db\Adapter\Adapter or Laminas\Db\Sql\Sql instance; paginates rows from a database.
    DbTableGatewayAccepts a Laminas\Db\TableGateway\AbstractTableGateway instance, and optionally additional arguments representing the WHERE, ORDER BY, GROUP BY, and/or HAVING clauases.
    IteratorAccepts any Iterator instance.
    NullFillDummy paginator.
    +

    To create a paginator instance, you must supply an adapter to the constructor:

    +
    use Laminas\Paginator\Adapter;
    +use Laminas\Paginator\Paginator;
    +
    +$paginator = new Paginator(new Adapter\ArrayAdapter($array));
    +

    In the case of the NullFill adapter, in lieu of a data collection you must +supply an item count to its constructor.

    +

    Although the instance is technically usable in this state, in your controller +action you'll need to tell the paginator what page number the user requested. +This allows advancing through the paginated data.

    +
    $paginator->setCurrentPageNumber($page);
    +

    The simplest way to keep track of this value is through a URL parameter. The +following is an example laminas-router +route configuration:

    +
    return [
    +    'routes' => [
    +        'paginator' => [
    +            'type' => 'segment',
    +            'options' => [
    +                'route' => '/list/[page/:page]',
    +                'defaults' => [
    +                    'page' => 1,
    +                ],
    +            ],
    +        ],
    +    ],
    +];
    +

    With the above route (and using laminas-mvc +controllers), you might set the current page number in your controller action +like so:

    +
    $paginator->setCurrentPageNumber($this->params()->fromRoute('page'));
    +

    There are other options available; see the Configuration chapter +for more on them.

    +

    Finally, you'll need to assign the paginator instance to your view. If you're +using laminas-mvc and laminas-view, you can assign the paginator object to your view +model:

    +
    $vm = new ViewModel();
    +$vm->setVariable('paginator', $paginator);
    +return $vm;
    +

    The DbSelect adapter

    +
    +

    Deprecated

    +

    The adapter is deprecated since version 2.10.0. Please use the laminas/laminas-paginator-adapter-laminasdb package if you wish to use the laminas-db-based pagination adapters.

    +

    Installation Requirements

    +

    The DbSelect adapter depends on the laminas-db component, so be sure to have it +installed before getting started:

    +
    $ composer require laminas/laminas-db
    +

    Database optimizations

    +

    Instead of selecting every matching row of a given query, the DbSelect adapter +retrieves only the smallest amount of data necessary for displaying the +current page. Because of this, a second query is dynamically generated to +determine the total number of matching rows.

    +
    +

    Most adapters receive their datasets directly. However, the DbSelect adapter +requires a more detailed explanation regarding the retrieval and count of the +data from the database.

    +

    You do not have to retrieve data from the database prior to using the DbSelect +adapter; the adapter will do the retrieval for you, as well as provide a count +of total pages. If additional work has to be done on the database results which +cannot be expressed via the provided Laminas\Db\Sql\Select, object you must +extend the adapter and override the getItems() method.

    +

    Additionally this adapter does not fetch all records from the database in +order to count them. Instead, the adapter manipulates the original query to +produce a corresponding COUNT query, and uses the new query to get the number +of rows. While this approach requires an extra round-trip to the database, +doing so is stillmany times faster than fetching an entire result set and using +count(), especially with large collections of data.

    +

    The database adapter will try and build the most efficient query that will +execute on pretty much any modern database. However, depending on your database +or even your own schema setup, there might be more efficient ways to get a +rowcount.

    +

    There are two approaches for doing this. The first is to extend the DbSelect +adapter and override the count() method:

    +
    class MyDbSelect extends DbSelect
    +{
    +    public function count()
    +    {
    +        if ($this->rowCount) {
    +            return $this->rowCount;
    +        }
    +
    +        $select = new Select();
    +        $select
    +          ->from('item_counts')
    +          ->columns(['c'=>'post_count']);
    +
    +        $statement = $this->sql->prepareStatementForSqlObject($select);
    +        $result    = $statement->execute();
    +        $row       = $result->current();
    +        $this->rowCount = $row['c'];
    +
    +        return $this->rowCount;
    +    }
    +}
    +
    +$adapter = new MyDbSelect($query, $adapter);
    +

    Alternately, you can pass an additional Laminas\Db\Sql\Select object as the +fourth constructor argument to the DbSelect adapter to implement a custom +count query.

    +

    For example, if you keep track of the count of blog posts in a separate table, +you could achieve a faster count query with the following setup:

    +
    use Laminas\Db\Sql\Select;
    +use Laminas\Paginator\Adapter\DbSelect;
    +use Laminas\Paginator\Paginator;
    +
    +$countQuery = new Select();
    +$countQuery
    +    ->from('item_counts')
    +    ->columns([ DbSelect::ROW_COUNT_COLUMN_NAME => 'post_count' ]);
    +
    +$adapter = new DbSelect($query, $dbAdapter, null, $countQuery);
    +$paginator = new Paginator($adapter);
    +

    Alternatively, the same can be achieved using the provided factory:

    +
    use Laminas\Paginator\Adapter\DbSelect;
    +use Laminas\Paginator\Factory as PaginatorFactory;
    +
    +$countQuery = new Select();
    +$countQuery
    +    ->from('item_counts')
    +    ->columns([ DbSelect::ROW_COUNT_COLUMN_NAME => 'post_count' ]);
    +
    +$paginator = PaginatorFactory::factory(
    +    [
    +        $query,
    +        $dbAdapter,
    +        null,
    +        $countQuery,
    +    ],
    +    DbSelect::class
    +);
    +

    This approach will probably not give you a huge performance gain on small +collections and/or simple select queries. However, with complex queries and +large collections, a similar approach could give you a significant performance +boost.

    +

    The DbSelect adapter also supports returning of fetched records using the +ResultSet subcomponent of laminas-db. +You can override the concrete ResultSet implementation by passing an object +implementing Laminas\Db\ResultSet\ResultSetInterface as the third constructor +argument to the DbSelect adapter:

    +
    use Laminas\Db\ResultSet\HydratingResultSet;
    +use Laminas\Paginator\Adapter\DbSelect;
    +use Laminas\Paginator\Paginator;
    +
    +// $objectPrototype is an instance of our custom entity
    +// $hydrator is a custom hydrator for our entity
    +// (implementing Laminas\Hydrator\HydratorInterface)
    +$resultSet = new HydratingResultSet($hydrator, $objectPrototype);
    +
    +$adapter = new DbSelect($query, $dbAdapter, $resultSet)
    +$paginator = new Laminas\Paginator\Paginator($adapter);
    +

    Now when we iterate over $paginator we will get instances of our custom entity +instead of associative arrays.

    +

    Rendering pages with view scripts

    +
    +

    Installation Requirements

    +

    The rendering with view scripts depends on the laminas-view component, so be sure +to have it installed before getting started:

    +
    $ composer require laminas/laminas-view
    +
    +

    The view script is used to render the page items (if you're using +laminas-paginator to do so) and display the pagination control.

    +

    Because Laminas\Paginator\Paginator implements the SPL interface +IteratorAggregate, you can loop over an +instance using foreach:

    +
    <html>
    +<body>
    +<h1>Example</h1>
    +<?php if (count($this->paginator)): ?>
    +<ul>
    +<?php foreach ($this->paginator as $item): ?>
    +  <li><?= $item; ?></li>
    +<?php endforeach; ?>
    +</ul>
    +<?php endif; ?>
    +
    +<?= $this->paginationControl(
    +    $this->paginator,
    +    'Sliding',
    +    'my_pagination_control',
    +    ['route' => 'application/paginator']
    +) ?>
    +</body>
    +</html>
    +

    Notice the view helper call near the end. PaginationControl accepts up to four +parameters: the paginator instance, a scrolling style, a view script name, and +an array of additional parameters.

    +

    The second and third parameters are very important. Whereas the view script name +is used to determine how the pagination control should look, the scrolling +style is used to control how it should behave. Say the view script is in the +style of a search pagination control, like the one below:

    +

    Pagination controls

    +

    What happens when the user clicks the "next" link a few times? Well, any number of things could +happen:

    +
      +
    • The current page number could stay in the middle as you click through (as it + does on Yahoo!)
    • +
    • It could advance to the end of the page range and then appear again on the + left when the user clicks "next" one more time.
    • +
    • The page numbers might even expand and contract as the user advances (or + "scrolls") through them (as they do on Google).
    • +
    +

    There are four scrolling styles packaged with Laminas:

    +
    + + + + + + + + + + + + + + + + + + + + + + + + +
    Scrolling styleDescription
    AllReturns every page. This is useful for dropdown menu pagination controls with relatively few pages. In these cases, you want all pages available to the user at once.
    ElasticA Google-like scrolling style that expands and contracts as a user scrolls through the pages.
    JumpingAs users scroll through, the page number advances to the end of a given range, then starts again at the beginning of the new range.
    SlidingA Yahoo!-like scrolling style that positions the current page number in the center of the page range, or as close as possible. This is the default style.
    +

    The fourth and final parameter is reserved for an optional associative array of +variables that you want available in your view (available via $this). For +instance, these values could include extra URL parameters for pagination links.

    +

    By setting the default view script name, default scrolling style, and view +instance, you can eliminate the calls to PaginationControl completely:

    +
    use Laminas\Paginator\Paginator;
    +use Laminas\View\Helper\PaginationControl;
    +
    +Paginator::setDefaultScrollingStyle('Sliding');
    +PaginationControl::setDefaultViewPartial('my_pagination_control');
    +

    When all of these values are set, you can render the pagination control inside +your view script by echoing the paginator instance:

    +
    <?= $this->paginator ?>
    +
    +

    Using other template engines

    +

    Of course, it's possible to use laminas-paginator with other template engines. +For example, with Smarty you might do the following:

    +
    $smarty-assign('pages', $paginator->getPages());
    +

    You could then access paginator values from a template like so:

    +
    {$pages.pageCount}
    +
    +

    Example pagination controls

    +

    The following example pagination controls will help you get started with +laminas-view:

    +

    Search pagination:

    +
    <!--
    +See http://developer.yahoo.com/ypatterns/pattern.php?pattern=searchpagination
    +-->
    +
    +<?php if ($this->pageCount): ?>
    +<div class="paginationControl">
    +<!-- Previous page link -->
    +<?php if (isset($this->previous)): ?>
    +  <a href="<?= $this->url($this->route, ['page' => $this->previous]); ?>">
    +    &lt; Previous
    +  </a> |
    +<?php else: ?>
    +  <span class="disabled">&lt; Previous</span> |
    +<?php endif; ?>
    +
    +<!-- Numbered page links -->
    +<?php foreach ($this->pagesInRange as $page): ?>
    +  <?php if ($page != $this->current): ?>
    +    <a href="<?= $this->url($this->route, ['page' => $page]); ?>">
    +        <?= $page; ?>
    +    </a> |
    +  <?php else: ?>
    +    <?= $page; ?> |
    +  <?php endif; ?>
    +<?php endforeach; ?>
    +
    +<!-- Next page link -->
    +<?php if (isset($this->next)): ?>
    +  <a href="<?= $this->url($this->route, ['page' => $this->next]); ?>">
    +    Next &gt;
    +  </a>
    +<?php else: ?>
    +  <span class="disabled">Next &gt;</span>
    +<?php endif; ?>
    +</div>
    +<?php endif; ?>
    +

    Item pagination:

    +
    <!--
    +See http://developer.yahoo.com/ypatterns/pattern.php?pattern=itempagination
    +-->
    +
    +<?php if ($this->pageCount): ?>
    +<div class="paginationControl">
    +<?= $this->firstItemNumber; ?> - <?= $this->lastItemNumber; ?>
    +of <?= $this->totalItemCount; ?>
    +
    +<!-- First page link -->
    +<?php if (isset($this->previous)): ?>
    +  <a href="<?= $this->url($this->route, ['page' => $this->first]); ?>">
    +    First
    +  </a> |
    +<?php else: ?>
    +  <span class="disabled">First</span> |
    +<?php endif; ?>
    +
    +<!-- Previous page link -->
    +<?php if (isset($this->previous)): ?>
    +  <a href="<?= $this->url($this->route, ['page' => $this->previous]); ?>">
    +    &lt; Previous
    +  </a> |
    +<?php else: ?>
    +  <span class="disabled">&lt; Previous</span> |
    +<?php endif; ?>
    +
    +<!-- Next page link -->
    +<?php if (isset($this->next)): ?>
    +  <a href="<?= $this->url($this->route, ['page' => $this->next]); ?>">
    +    Next &gt;
    +  </a> |
    +<?php else: ?>
    +  <span class="disabled">Next &gt;</span> |
    +<?php endif; ?>
    +
    +<!-- Last page link -->
    +<?php if (isset($this->next)): ?>
    +  <a href="<?= $this->url($this->route, ['page' => $this->last]); ?>">
    +    Last
    +  </a>
    +<?php else: ?>
    +  <span class="disabled">Last</span>
    +<?php endif; ?>
    +
    +</div>
    +<?php endif; ?>
    +

    Dropdown pagination:

    +
    <?php if ($this->pageCount): ?>
    +<select id="paginationControl" size="1">
    +<?php foreach ($this->pagesInRange as $page): ?>
    +  <?php $selected = ($page == $this->current) ? ' selected="selected"' : ''; ?>
    +  <option value="<?= $this->url($this->route, ['page' => $page]);?>"<?= $selected ?>>
    +    <?= $page; ?>
    +  </option>
    +<?php endforeach; ?>
    +</select>
    +<?php endif; ?>
    +
    +<script type="text/javascript"
    +     src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js">
    +</script>
    +<script type="text/javascript">
    +$('paginationControl').observe('change', function() {
    +    window.location = this.options[this.selectedIndex].value;
    +})
    +</script>
    +

    Listing of properties

    +

    The following options are available to pagination control view scripts:

    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    PropertyTypeDescription
    firstintegerFirst page number (typically 1).
    firstItemNumberintegerAbsolute number of the first item on this page.
    firstPageInRangeintegerFirst page in the range returned by the scrolling style.
    currentintegerCurrent page number.
    currentItemCountintegerNumber of items on this page.
    itemCountPerPageintegerMaximum number of items available to each page.
    lastintegerLast page number.
    lastItemNumberintegerAbsolute number of the last item on this page.
    lastPageInRangeintegerLast page in the range returned by the scrolling style.
    nextintegerNext page number.
    pageCountintegerNumber of pages.
    pagesInRangearrayArray of pages returned by the scrolling style.
    previousintegerPrevious page number.
    totalItemCountintegerTotal number of items.
    + + + + + + + + + +
    + +
    +
    + + + + + + + + + + + + + + + +