最近用PHP DOO框架做了个搜索引擎网站的前端,过程中发现了一个分页helper——DooPager的缺陷。
取到的记录很多的时候,pager工作起来特别慢,后来经过查看源码,解决了该问题。
问题描述:
/**
* Paginate the list of items and prepare pager components to be use in View.
*
* @param int $page The current page number
* @param int $itemPerPage Items per page
* @return array An array of pager component, access via <strong>pages, jump_menu, page_size, current_page, total_page, next_link, prev_link</strong>
*/
public function paginate($page, $itemPerPage=0)
问题出在这个方法里面。原因是如果返回的记录很多。例如经过分页计算得出总共有百万级的页面数,这个方法把所有的页面号都遍历了一遍,造成了浪费。其实只要判断出
当前页面号大于分页中的range中的最大值之后,跳出循环即可。
不多说,直接上代码
for($i=1;$i<=$this->totalPage;){ //原来这里是for($i=1;$i<=$this->totalPage;$i++)
// loop through all pages. if first, last, or in range, display
if($i==1 || $i==$this->totalPage || in_array($i,$range)){
$lastDot = '';
if($modulus==1){
if($i==$this->totalPage && $this->currentPage<($this->totalPage-($this->maxLength-$center-$modulus)))
$lastDot = '...';
}else{
if($i==$this->totalPage && $this->currentPage<=($this->totalPage-($this->maxLength-$center)))
$lastDot = '...';
}
$this->output .= ($i == $this->currentPage) ? "<a class =\"{$this->currentCss}\" href=\"javascript:void(0);\">$i":"<a class=\"{$this->pagesCss}\" href=\"{$this->baseUrl}/$i\">$lastDot $i";
if($range[0] > 2 && $i == 1)
$this->output .= " ...</a> ";
else
$this->output .= '</a> ';
//如果已经到最后一个页号,跳出循环
if($i == $this->totalPage)
break;
}
//以下部分为新增的部分,用于修改counter $i
if($i <= $range[count($range)-1] )
$i++;
else
$i = $this->totalPage;
}