php实现分页类

PHP 分页类实现
分页功能在Web开发中非常常见,可以通过封装一个分页类来简化代码。以下是一个完整的PHP分页类实现方案:
分页类基本结构
class Pagination {
private $totalItems;
private $itemsPerPage;
private $currentPage;
private $totalPages;
private $pageRange = 5;
private $url;
public function __construct($totalItems, $itemsPerPage, $currentPage, $url = '') {
$this->totalItems = $totalItems;
$this->itemsPerPage = $itemsPerPage;
$this->currentPage = max(1, min($currentPage, $this->getTotalPages()));
$this->url = $url;
}
public function getTotalPages() {
return ceil($this->totalItems / $this->itemsPerPage);
}
}
核心分页逻辑
public function getPaginationLinks() {
$links = [];
$totalPages = $this->getTotalPages();
// 上一页
if ($this->currentPage > 1) {
$links[] = [
'page' => $this->currentPage - 1,
'text' => '上一页',
'active' => false
];
}
// 页码链接
$start = max(1, $this->currentPage - floor($this->pageRange / 2));
$end = min($totalPages, $start + $this->pageRange - 1);
for ($i = $start; $i <= $end; $i++) {
$links[] = [
'page' => $i,
'text' => $i,
'active' => ($i == $this->currentPage)
];
}
// 下一页
if ($this->currentPage < $totalPages) {
$links[] = [
'page' => $this->currentPage + 1,
'text' => '下一页',
'active' => false
];
}
return $links;
}
URL生成方法
public function getPageUrl($page) {
if (strpos($this->url, '?') !== false) {
return $this->url . '&page=' . $page;
} else {
return $this->url . '?page=' . $page;
}
}
数据库分页查询
public function getLimitOffset() {
$offset = ($this->currentPage - 1) * $this->itemsPerPage;
return [
'limit' => $this->itemsPerPage,
'offset' => $offset
];
}
完整使用示例
// 假设总记录数为100,每页显示10条,当前第3页
$totalItems = 100;
$itemsPerPage = 10;
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$url = 'http://example.com/list.php';
$pagination = new Pagination($totalItems, $itemsPerPage, $currentPage, $url);
$links = $pagination->getPaginationLinks();
// 数据库查询
$limitData = $pagination->getLimitOffset();
$sql = "SELECT * FROM items LIMIT {$limitData['limit']} OFFSET {$limitData['offset']}";
// 显示分页链接
foreach ($links as $link) {
$class = $link['active'] ? 'active' : '';
echo "<a href='{$pagination->getPageUrl($link['page'])}' class='$class'>{$link['text']}</a> ";
}
样式优化建议
.pagination a {
display: inline-block;
padding: 5px 10px;
margin: 0 2px;
border: 1px solid #ddd;
text-decoration: none;
}
.pagination a.active {
background-color: #007bff;
color: white;
border-color: #007bff;
}
.pagination a:hover:not(.active) {
background-color: #ddd;
}
高级功能扩展
- 添加首页和尾页链接
- 支持AJAX分页
- 添加每页显示数量选择器
- 支持URL美化(如/page/2)
- 添加总记录数显示
- 支持多参数URL处理
这个分页类提供了基本的分页功能,可以根据项目需求进行扩展和定制。使用时只需要实例化类并调用相应方法即可实现分页功能。







