php oop实现分页
PHP OOP 实现分页
分页是Web开发中常见的功能,使用面向对象编程(OOP)可以更好地组织代码。以下是实现分页的步骤:
创建分页类
定义一个 Pagination 类,包含分页逻辑的核心方法:

class Pagination {
private $totalItems;
private $itemsPerPage;
private $currentPage;
private $totalPages;
private $maxPagesToShow = 5;
public function __construct($totalItems, $itemsPerPage, $currentPage) {
$this->totalItems = $totalItems;
$this->itemsPerPage = $itemsPerPage;
$this->currentPage = $currentPage;
$this->calculateTotalPages();
}
private function calculateTotalPages() {
$this->totalPages = ceil($this->totalItems / $this->itemsPerPage);
}
public function getOffset() {
return ($this->currentPage - 1) * $this->itemsPerPage;
}
public function getPages() {
$pages = [];
$half = floor($this->maxPagesToShow / 2);
$startPage = max(1, $this->currentPage - $half);
$endPage = min($this->totalPages, $startPage + $this->maxPagesToShow - 1);
if ($endPage - $startPage + 1 < $this->maxPagesToShow) {
$startPage = max(1, $endPage - $this->maxPagesToShow + 1);
}
for ($i = $startPage; $i <= $endPage; $i++) {
$pages[] = $i;
}
return $pages;
}
public function getCurrentPage() {
return $this->currentPage;
}
public function getTotalPages() {
return $this->totalPages;
}
}
使用分页类
在控制器或业务逻辑中实例化并使用分页类:
$totalItems = 100; // 从数据库获取总记录数
$itemsPerPage = 10;
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$pagination = new Pagination($totalItems, $itemsPerPage, $currentPage);
$offset = $pagination->getOffset();
// 使用 $offset 和 $itemsPerPage 查询数据库
// $sql = "SELECT * FROM table LIMIT $offset, $itemsPerPage";
渲染分页链接
在视图中渲染分页导航:

$pages = $pagination->getPages();
$currentPage = $pagination->getCurrentPage();
$totalPages = $pagination->getTotalPages();
echo '<div class="pagination">';
if ($currentPage > 1) {
echo '<a href="?page=' . ($currentPage - 1) . '">Previous</a>';
}
foreach ($pages as $page) {
$active = $page == $currentPage ? 'active' : '';
echo '<a href="?page=' . $page . '" class="' . $active . '">' . $page . '</a>';
}
if ($currentPage < $totalPages) {
echo '<a href="?page=' . ($currentPage + 1) . '">Next</a>';
}
echo '</div>';
数据库查询示例
结合分页类实现数据库查询:
class Database {
public function getPaginatedData($table, $offset, $limit) {
// 使用 PDO 或其他数据库驱动
$stmt = $pdo->prepare("SELECT * FROM $table LIMIT :offset, :limit");
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll();
}
}
$db = new Database();
$data = $db->getPaginatedData('users', $offset, $itemsPerPage);
分页样式
添加CSS样式美化分页导航:
.pagination {
display: flex;
gap: 5px;
margin-top: 20px;
}
.pagination a {
padding: 8px 12px;
border: 1px solid #ddd;
text-decoration: none;
}
.pagination a.active {
background-color: #007bff;
color: white;
}
通过以上步骤,可以实现一个灵活且可复用的OOP分页功能。根据实际需求,可以进一步扩展分页类,例如添加URL生成、自定义样式等功能。






