class Paging
{
//记录的总条数
protected $total;
//每一页的条数
protected $pageSize;
//当前页
protected $page;
//页码的参数名字
protected $pageName;
//总页数
protected $pageCount;
//基本URL
protected $url;
/**
* [__construct description]
* @param [type] $total [总页数]
* @param integer $pageSize [每一页的条数]
* @param string $pageName [页码参数的名字]
*/
public function __construct($total, $pageSize=5, $pageName='page')
{
$this->total = $total;
$this->pageSize = $pageSize;
$this->pageCount = ceil($total / $pageSize);
$this->pageName = $pageName;
$this->url = $this->getUrl();
$this->page = $this->getPage();
}
public function headPage()
{
return $this->setUrl(1);
}
public function prevPage()
{
if ($this->page < 2) {
$page = 1;
} else {
$page = $this->page - 1;
}
return $this->setUrl($page);
}
public function nextPage()
{
if ($this->page < $this->pageCount) {
$page = $this->page + 1;
} else {
$page = $this->pageCount;
}
return $this->setUrl($page);
}
public function tailPage()
{
return $this->setUrl($this->pageCount);
}
public function givenPage($page)
{
if ($page < 1) {
$page = 1;
} else if ($page > $this->pageCount) {
$page = $this->pageCount;
}
return $this->setUrl($page);
}
public function listed()
{
return [
'head'=>$this->headPage(),
'prev'=>$this->prevPage(),
'next'=>$this->nextPage(),
'tail'=>$this->tailPage()
];
}
protected function getPage()
{
//我们约定,确定页码的参数默认是page
if (empty($_GET[$this->pageName])) {
return 1;
}
$page = (int)$_GET[$this->pageName];
if ($page < 1) {
$page = 1;
} else if ($page > $this->pageCount) {
$page = $this->pageCount;
}
return $page;
}
protected function getUrl()
{
//获取协议
$url = $_SERVER['REQUEST_SCHEME'] . '://';
//拼接主机
$url .= $_SERVER['HTTP_HOST'];
//拼接端口
$url .= ':' . $_SERVER['SERVER_PORT'];
//拼接URI
$requestUri = $_SERVER['REQUEST_URI'];
if (isset($_GET[$this->pageName])) {
$replaceStr = $this->pageName . '=' . $_GET[$this->pageName];
$replaceArr = [
$replaceStr.'&',
'&'.$replaceStr,
'?'.$replaceStr
];
$requestUri = str_replace($replaceArr, '', $requestUri);
}
return $url . $requestUri;
}
protected function setUrl($page)
{
if (strpos($this->url, '?')) {
return $this->url . '&' . $this->pageName . '=' . $page;
} else {
return $this->url . '?' . $this->pageName . '=' . $page;
}
}
}
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。互联网+时代,时刻要保持学习,携手千锋PHP,Dream It Possible。
网友评论