PEAR is archived and read-only

This mirror preserves historical PEAR package releases and metadata so existing references remain available.

Home » HTML » Pager » Manual

Data paging class which also builds links to the pages.

Introduction

Introduction – Usage of Pager 2.x

What is Pager?

Pager is a class to page an array of data. It is taken as input and it is paged according to various parameters. Pager also builds links within a specified range, and allows complete customization of the output (it even works with mod_rewrite). It is compatible with Pager v.1.x and Pager_Sliding API

Example 1

This simple example will page the array of alphabetical letters, giving back pages with 3 letters per page, and links to the previous two / next two pages:

<?php
require_once 'Pager.php';
$params = array(
    'mode'       => 'Jumping',
    'perPage'    => 3,
    'delta'      => 2,
    'itemData'   => array('a','b','c','d','e',[...omissis...],'z')
);
$pager = & Pager::factory($params);
$data  = $pager->getPageData();
$links = $pager->getLinks();
//$links is an ordered+associative array with 'back'/'pages'/'next'/'first'/'last'/'all' links.
//NB: $links['all'] is the same as $pager->links;

//echo links to other pages:
echo $links['all'];

//Pager can also generate <link rel="first|prev|next|last"> tags
echo $pager->linkTags;

//Show data for current page:
echo 'PAGED DATA: ' ; print_r($data);

//Results from methods:
echo 'getCurrentPageID()...: '; var_dump($pager->getCurrentPageID());
echo 'getNextPageID()......: '; var_dump($pager->getNextPageID());
echo 'getPreviousPageID()..: '; var_dump($pager->getPreviousPageID());
echo 'numItems()...........: '; var_dump($pager->numItems());
echo 'numPages()...........: '; var_dump($pager->numPages());
echo 'isFirstPage()........: '; var_dump($pager->isFirstPage());
echo 'isLastPage().........: '; var_dump($pager->isLastPage());
echo 'isLastPageComplete().: '; var_dump($pager->isLastPageComplete());
echo '$pager->range........: '; var_dump($pager->range);
?>

In case you're wondering, $pager->range is a numeric array; its keys are the numbers of the pages in the current range, and the matching values are booleans (TRUE if its key represents currentPage, FALSE otherwise). This array can be useful to build the links manually, e.g. when using a template engine.

Example 2

This example shows how you can use this class with mod_rewite. Let's suppose we have a .htaccess like this:


---------
RewriteEngine on
#Options FollowSymlinks

RewriteBase /
RewriteRule ^articles/([a-z]{1,12})/art([0-9]{1,4})\.html$ /article.php?num=$2&amp;month=$1 [L]
---------

It should transform an url like "/articles/march/art15.html" into "/article.php?num=15&month=march"

<?php
require_once 'Pager.php';

$month = 'september';
$params = array(
    'mode'      => 'Sliding',
    'append'    => false,
    'urlVar'    => 'num',
    'path'      => 'http://myserver.com/articles/' . $month,
    'fileName'  => 'art%d.html',  //Pager replaces "%d" with page number...
    'itemData'  => array('a','b','c',[...omissis...],'z'),
    'perPage'   => 3
);
$pager = & Pager::factory($params);

$data  = $pager->getPageData();
echo $pager->links;
echo 'Data for current page: '; print_r($data);
?>

More pagers in a single page

Using more than one pager in a single page is as simple as using a different urlVar for each pager:

<?php
require_once 'Pager.php';

//first pager
$params1 = array(
    'perPage'    => 3,
    'urlVar'     => 'pageID_articles',  //1st identifier
    'itemData'   => $someArray
);
$pager1 = & Pager::factory($params1);
$data1  = $pager1->getPageData();
$links1 = $pager1->getLinks();

//second pager
$params2 = array(
    'perPage'    => 8,
    'urlVar'     => 'pageID_news',      //2nd identifier
    'itemData'   => $someOtherArray
);
$pager2 = & Pager::factory($params2);
$data2  = $pager2->getPageData();
$links2 = $pager2->getLinks();
?>

Pager and big db resultsets

If you want to paginate db resultsets, fetching them all into an array and passing it to Pager might not be the best option. You can still leverage Pager and have good performances using a wrapper. There is a sample wrapper for each one of the PEAR db abstraction systems in the /examples/ dir of the package. You may use it as-is or customize it to your needs.

Adding extra variables to the querystring

If you need to add some extra variables to the querystring, use the extraVars parameter:

<?php
$params = array(
    'extraVars' => array(
        'firstKey'  => 'firstValue',
        'secondKey' => 'secondValue',
        //...
    ),
    //...
);
$pager1 = & Pager::factory($params);
?>

Important note for PHP 5 users

Since version 2.2.1, Pager works with PHP 5 too, but you must use the factory() method instead of the constructor (which is deprecated):

<?php
require_once 'Pager.php';

//wrong: 
//$pager =& new Pager($params);

//right
$pager =& Pager::factory($params);

//continue as you did before
?>

If you are using a previous revision and cannot update, you must write the following code on PHP 5:

<?php
//chose your preferred mode [Jumping | Sliding]:

//require_once 'Pager/Jumping.php';
require_once 'Pager/Sliding.php';

//$pager =& new Pager_Jumping($params);
$pager =& new Pager_Sliding($params);

//continue as you did before
?>

Pager Tutorials

There are some other online resources with in-depth coverage of what Pager can do: PEAR::Pager tutorials.

Pager "Jumping" vs. "Sliding"

Pager "Jumping" vs. "Sliding" – Feature comparison of the two pager styles

What are the differences between the two styles?

Since an example is worth 1000 words:

"Jumping" Pager logic

Let's suppose that the data spans on 15 pages, and the window width is 5 page links. The links are built on "frames" of 5 pages each: [1-5] [6-10] [11-15] Pager in "Jumping" mode always shows the same 5 page links while you are on one of these pages. Here's a temporal succession of the links, starting from page 1 and moving forward. There are brakets around current page number to highlight this:

<?php
a)    {1} 2  3  4  5  =>   // first frame: [1-5]
b) <=  1 {2} 3  4  5  =>
c) <=  1  2 {3} 4  5  =>
d) <=  1  2  3 {4} 5  =>
e) <=  1  2  3  4 {5} =>   // HERE IT JUMPS TO THE NEXT FRAME
f) <= {6} 7  8  9 10  =>   // second frame: [6-10]
g) <=  6 {7} 8  9 10  =>
h) <=  6  7 {8} 9 10  =>
?>

and so on. See what a "jumping window" frame is? When you reach a limit (in the example, you go from page 5 to page 6), it "jumps" to next frame (links from page 6 to 10).

"Sliding" Pager logic

Instead of jumping from one frame to the other, with Pager in "Sliding" mode the change is done smoothly, and the current page is always shown at the center of the "window" (except of course for the first and the last pages):

<?php
a)       {1} 2  3  4  5  => [15]
b) [1] <= 1 {2} 3  4  5  => [15]
c) [1] <= 1  2 {3} 4  5  => [15]  // HERE IT's STARTING WORKING AS DESIGNED
d) [1] <= 2  3 {4} 5  6  => [15]  // see: current page number is at the center of the window
e) [1] <= 3  4 {5} 6  7  => [15]  // and it stays there...
f) [1] <= 4  5 {6} 7  8  => [15]
g) [1] <= 5  6 {7} 8  9  => [15]
h) [1] <= 6  7 {8} 9 10  => [15]
?>

and so on.

Other differences

Apart from the different "philosophy", there is one difference in the delta parameter: in "Jumping" mode, it's the number of page numbers to show; in "Sliding" mode it's the number of page numbers to show before and after the current one.

Pager::factory

Pager::factory() – Creates a pager instance

Synopsis

require_once 'Pager.php';

object &factory ( array $options )

Parameter

Pager::factory() method takes an associative array of parameters as input values. This is the complete list of these options:

REQUIRED options are:

Return value

object - a specific Pager instance or a PEAR_Error object, if fails

Pager::setOptions

Pager::setOptions() – Set or change option after the Pager object has been constructed

Synopsis

require_once 'Pager.php';

array Pager::setOptions ( array $options )

Description

Remember to call build() after this method to regenerate the data and the links.

Parameter

Return value

return PAGER_OK constant on success

Pager::build

Pager::build() – Generate or refresh the links and paged data after a call to setOptions()

Synopsis

require_once 'Pager.php';

array Pager::build ( )

Description

Pager::getCurrentPageID

Pager::getCurrentPageID() – Returns current page number

Synopsis

require_once 'Pager.php';

integer getCurrentPageID ( )

Return value

integer - Current page number.

Pager::getNextPageID

Pager::getNextPageID() – Returns next page number.

Synopsis

require_once 'Pager.php';

mixed Pager::getNextPageID ( )

Description

If current page is last page this function returns FALSE, otherwise returns next page number.

Return value

return Next page number or FALSE

Pager::getOffsetByPageId

Pager::getOffsetByPageId() – Returns offsets for given pageID.

Synopsis

require_once 'Pager.php';

array Pager::getOffsetByPageId ( integer $pageid = null )

Description

Returns offsets for given pageID. Eg, if you pass it pageID one and your perPage limit is 10 it will return (1, 10). pageID=2 would give you (11, 20).

if the method is called without parameter, pageID is set to currentPage

Parameter

Return value

return array with first and last offsets

Deprecated

deprecated

Pager::getPageData

Pager::getPageData() – Returns an array of current pages data

Synopsis

require_once 'Pager.php';

array Pager::getPageData ( integer $pageID = null )

Parameter

Return value

return array of data for this page.

Pager::getPageIdByOffset

Pager::getPageIdByOffset() – Returns the page number for the given offset

Synopsis

require_once 'Pager.php';

array Pager::getPageIdByOffset ( integer $index )

Description

This method is only available in "Jumping" mode.

Parameter

Return value

return Page number for this offset

Pager::getPageRangeByPageId

Pager::getPageRangeByPageId() – Returns offsets for given pageID.

Synopsis

require_once 'Pager.php';

array Pager::getPageRangeByPageId ( integer $pageid = null )

Description

Given a PageId, it returns the limits of the range of pages displayed. While getOffsetByPageId() returns the offset of the data within the current page, this method returns the offsets of the page numbers interval.

E.g., in "Jumping" mode, if you have pageId=3 and delta=10, it will return (1, 10). pageID=8 would give you (1, 10) as well, because 1 <= 8 <= 10. pageID=11 would give you (11, 20).

In "Sliding" mode, if you have pageId=5 and delta=2, it will return (3, 7). pageID of 9 would give you (4, 8).

if the method is called without parameter, pageID is set to currentPage number

Parameter

Return value

return array with first and last offsets

Pager::getPageSelectBox

Pager::getPageSelectBox() – Returns a string with a XHTML SELECT menu, to choose the page to display.

Synopsis

require_once 'Pager.php';

array Pager::getPageSelectBox ( array $params , string $extraAttributes = '' )

Parameter

Description

Returns a string with a XHTML SELECT menu with the page numbers, useful as an alternative to the links

Example

This example shows how you can create a select box to let your users choose the number of the page to go to.

<?php
include 'Pager.php';

$params = array(
    'mode'       => 'Jumping',
    'perPage'    => 3,
    'delta'      => 2,
    'itemData'   => array('a','b','c','d','e',[...omissis...],'z'),
);
$pager = & Pager::factory($params);

$selectBoxParams = array(
    'optionText' => 'page %d',
    'autoSubmit' => true,
);
$selectBox = $pager->getPageSelectBox();

echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF']) . '" method="GET">';
echo $selectBox;
echo '<input type="submit" value="submit" />';
echo '</form>';
?>

Return value

return string with the XHTML SELECT menu.

Pager::getPreviousPageID

Pager::getPreviousPageID() – Returns previous page number.

Synopsis

require_once 'Pager.php';

mixed Pager::getPreviousPageID ( )

Description

If current page is first page this function returns FALSE, otherwise returns previous page number.

Return value

return Previous page number or FALSE.

Pager::getPerPageSelectBox

Pager::getPerPageSelectBox() – Returns a string with a XHTML SELECT menu, to choose how many items per page should be displayed.

Synopsis

require_once 'Pager.php';

array Pager::getPerPageSelectBox ( integer $start = 5 , integer $end = 30 , integer $step = 5 , boolean $showAllData = false , string $optionText = '%d' )

Parameter

Description

Returns a string with a XHTML SELECT menu, useful for letting the user choose how many items per page should be displayed. If parameter useSessions is TRUE, this value is stored in a session var. The string isn't echoed right away so you can use it with template engines.

Example

This example shows how you can create a select box to let your users choose the number of items to display on each page.

<?php
include 'Pager/Pager.php';

$params = array(
    'mode'       => 'Jumping',
    'perPage'    => 3,
    'delta'      => 2,
    'itemData'   => array('a','b','c','d','e',[...omissis...],'z')
);
$pager = & Pager::factory($params);

$selectBox = $pager->getPerPageSelectBox();

echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF']) . '" method="GET">';
echo $selectBox;
echo '<input type="submit" value="submit" />';
echo '</form>';
?>

Return value

return string with the XHTML SELECT menu.

Pager::isFirstPage

Pager::isFirstPage() – Returns whether current page is first page

Synopsis

require_once 'Pager.php';

bool Pager::isFirstPage ( )

Return value

return TRUE or FALSE, wrt it is the first page or not.

Pager::isLastPage

Pager::isLastPage() – Returns whether current page is last page

Synopsis

require_once 'Pager.php';

bool Pager::isLastPage ( )

Return value

return TRUE or FALSE, wrt it is the last page or not.

Pager::isLastPageComplete

Pager::isLastPageComplete() – Returns whether last page is complete

Synopsis

require_once 'Pager.php';

bool Pager::isLastPageComplete ( )

Return value

return TRUE or FALSE, wrt the last page is complete (i.e. it has perPage values in the array for the last page) or not.

Pager::numItems

Pager::numItems() – Returns number of items

Synopsis

require_once 'Pager.php';

int Pager_Sliding::numItems ( )

Return value

return integer - Number of items

Pager::numPages

Pager::numPages() – Returns number of pages

Synopsis

require_once 'Pager.php';

int Pager_Sliding::numPages ( )

Return value

return integer - Number of pages

Pager::Pager

Pager::Pager() – Creates a pager instance

Synopsis

require_once 'Pager.php';

object &Pager ( array $options )

Deprecated

The constructor is deprecated in favour of the new factory() method, which is PHP5 compatible too.

Parameter

Pager constructor takes an associative array of parameters as input values. This is the complete list of these options:

REQUIRED options are:

Return value

object - a specific Pager instance or a PEAR_Error object, if fails