<?php
namespace lib;
class Paginator {
//总记录
private $total;
//每页显示多少条
private $limit;
//当前页码
private $page;
//总页码
private $pcount;
//地址
private $url;
//两边保持数字分页的
private $both_num;
/**
* 构造
*/
public function __construct($total, $limit) {
$this->total = $total ? $total : 0;
$this->limit = $limit;
$this->pcount = ceil($this->total / $this->limit);
$this->page = $this->setPage();
$this->url = $this->setUrl();
$this->both_num = 2;
if ($this->page >= $this->pcount) {
$this->page = $this->pcount;
}
}
/*
* 分页信息
*/
public function showPage() {
$page = $this->prev();
$page .= $this->first();
$page .= $this->pageList();
$page .= $this->last();
$page .= $this->next();
return $page;
}
/*
* 获取当前页码
*/
private function setPage() {
if (isset($_POST['page'])) {
if ($_POST['page'] > 0) {
if ($_POST['page'] > $this->pcount) {
return $this->pcount;
} else {
return $_POST['page'];
}
} else {
return 1;
}
} else {
return 1;
}
}
/*
* 获取地址
*/
private function setUrl() {
$url = $_SERVER['REQUEST_URI'];
$par = parse_url($url);
if (isset($par['query'])) {
parse_str($par['query'], $query);
unset($query['page']);
if ($query) {
$url = $par['path'] . '?' . http_build_query($query) . '&';
} else {
$url = $par['path'] . '?';
}
} else {
$url = $par['path'] . '?';
}
return $url;
}
/*
* 数字页码
*/
private function pageList() {
$plist = '';
for ($i = $this->both_num; $i >= 1; $i--) {
$page = $this->page - $i;
if ($page < 1) continue;
$plist.= '<a data-page-num="' . $page . '" href="javascript:;">' . $page . '</a>';
}
$plist.= '<a href="javascript:;" class="cur">' . $this->page . '</a>';
for ($i = 1; $i <= $this->both_num; $i++) {
$page = $this->page + $i;
if ($page > $this->pcount) break;
$plist .= '<a data-page-num="' . $page . '" href="javascript:;">' . $page . '</a>';
}
return $plist;
}
/*
* 首页
*/
private function first() {
if ($this->page > $this->both_num + 1) {
return '<a data-page-num="1" href="javascript:;">1</a><a href="javascript:;">…</a>';
}
}
/*
* 上一页
*/
private function prev() {
if ($this->page == 1) {
return '';
}
return '<a data-page-num="' . ($this->page - 1) . '" href="javascript:;">上一页</a>';
}
/*
* 下一页
*/
private function next() {
if ($this->page == $this->pcount) {
return '';
}
return '<a data-page-num="' . ($this->page + 1) . '" href="javascript:;">下一页</a>';
}
/*
* 尾页
*/
private function last() {
if ($this->pcount - $this->page > $this->both_num) {
return '<a href="javascript:;">…</a><a data-page-num="' . $this->pcount . '" href="javascript:;">' . $this->pcount . '</a>';
}
}
}
thinkphp自定义分页类
于 2022-01-09 18:01:55 首次发布