Pear::Pager分页类简介

12/22/2008来源:PHP技巧人气:5847

Pear的Pager分页类是一个很好用的php分页类,扩展性很强,能够适应各种分页情况的需求,至少我在几年间大大小小的项目里,基本上没有为分页额外写过代码,全部都是用的Pager,足见Pager的可用性之强.下面用代码来看看它的使用范例:

例子1
PLAIN TEXT
PHP:
<?php
require_once'Pager/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);
?>
Pager的使用,只要调整$param数组的参数,就可以应付很多种分页情况了.代码中的$links数组包含了一些链接,如上一页/页码/下一页/第一页/末页/全部.

例2
如今许多网站为了SEO,把动态页使用rewrite规则伪造成静态页的形式,例如下面这个.htaccess配置:

RewriteEngine on
#Options FollowSymlinks

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

即使在这种情况下,Pager分页仍然有办法工作,见下面的code

PLAIN TEXT
PHP:
<?php
require_once'Pager/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();
?>
通过配置$param,就能够把链接 "/articles/march/art15.html"对应到链接"/article.php?num=15&month=march" ,比较灵活的表现

扩展性
Pager类的扩展性,平心而论,也是不错的.比如以前写的path方式的分页类 - Pager::Pathing(),这个方法就是从Pager上扩展而来,满足了当时的需求.

作者:volcano发表于9月 22, 2006 at 7:16 am

版权信息:可以任意转载, 转载时请务必以超链接形式标明文章原始出处和作者信息及此声明

永久链接 - http://www.ooso.net/index.php/archives/250