类文件
<?php
$path = new Page(5, 51);
var_dump($path->allUrl());
var_dump($path->limit());
/**
* 分页类
*/
class Page
{
// 每页显示的条数
protected $number;
// 一共有多少条
protected $totalCount;
// 当前页
protected $page;
// 总页数
protected $totalPage;
// url
protected $url;
function __construct($number, $totalCount)
{
// 每页显示条数
$this->number = $number;
// 总条数
$this->totalCount = $totalCount;
// 总页数
$this->totalPage = $this->getTotalPage();
// 当前页数
$this->page = $this->getPage();
// 得到url
$this->url = $this->getUrl();
}
// 获取总页数
protected function getTotalPage()
{
$page = ceil($this->totalCount / $this->number);
$page = $page >=1 ? $page : 1;
return $page;
}
// 获取当前页数
protected function getPage()
{
if(empty($_GET['page'])){
$page = 1;
}else if($_GET['page'] > $this->totalPage){
$page = $this->totalPage;
}else if($_GET['page'] < 1){
$page = 1;
}else{
$page = $_GET['page'];
}
return $page;
}
// 获取url
protected function getUrl()
{
// 协议名
$scheme = $_SERVER['REQUEST_SCHEME'];
// 主机名
$host = $_SERVER['SERVER_NAME'];
// 端口号
$port = $_SERVER['SERVER_PORT'];
// 得到路径和请求字符串
$uri = $_SERVER['REQUEST_URI'];
// 清空page参数
$uriArray = parse_url($uri);
$path = $uriArray['path'];
if(!empty($uriArray['query'])){
parse_str($uriArray['query'], $array);
unset($array['page']);
$query = http_build_query($array);
if($query != ''){
$path = $path . '?' .$query;
}
}
return $scheme . '://' . $host . ':' . $port . $path;
}
// 设置url
protected function setUrl($str)
{
if(strstr($this->url, '?')){
$url = $this->url.'&'.$str;
}else{
$url = $this->url.'?'.$str;
}
return $url;
}
// 所有链接
public function allUrl()
{
return [
'first' => $this->first(),
'prev' => $this->prev(),
'next' => $this->next(),
'end' => $this->end(),
];
}
// 第一页
public function first()
{
return $this->setUrl('page=1');
}
// 下一页
public function next()
{
if($this->page + 1 > $this->totalPage){
$page = $this->totalPage;
}else{
$page = $this->page + 1;
}
return $this->setUrl('page='.$page);
}
// 上一页
public function prev()
{
if($this->page -1 < 1){
$page = 1;
}else{
$page = $this->page - 1;
}
return $this->setUrl('page='.$page);
}
// 最后一页
public function end()
{
return $this->setUrl('page='.$this->totalPage);
}
// limit 0,5
public function limit()
{
$offset = ($this->page - 1) * $this->number;
return $offset . ',' . $this->number;
}
}