<?php
class Paginator {
private int $page; // 當前頁
private int $perPage; // 每頁筆數
private int $total; // 總筆數
private string $urlPattern; // URL 模板,{page} 為佔位符
private int $pageRange; // 頁碼區塊顯示頁數(建議奇數)
public function __construct(int $total, int $perPage = 15, int $page = 1, string $urlPattern = '', int $pageRange = 7) {
$this->total = max(0, $total);
$this->perPage = max(1, $perPage);
$this->pageRange = $pageRange % 2 ? $pageRange : $pageRange + 1; // 確保奇數
$this->page = $this->normalizePage($page);
$this->urlPattern = $urlPattern ?: $this->detectUrlPattern();
}
private function normalizePage(int $page): int {
$lastPage = $this->lastPage();
return max(1, min($page, $lastPage ?: 1));
}
public function lastPage(): int {
return (int)ceil($this->total / $this->perPage);
}
public function offset(): int {
return ($this->page - 1) * $this->perPage;
}
public function limit(): int {
return $this->perPage;
}
// 自動偵測當前 URL 並生成含 {page} 佔位符的模板
private function detectUrlPattern(): string {
$uri = $_SERVER['REQUEST_URI'] ?? '/';
$parts = parse_url($uri);
$query = $parts['query'] ?? '';
parse_str($query, $qs);
$qs['page'] = '{page}';
$newQuery = http_build_query($qs);
return ($parts['path'] ?? '/') . ($newQuery ? '?' . $newQuery : '');
}
public function url(int $page): string {
return str_replace('{page}', (string)$page, $this->urlPattern);
}
// 獲取頁碼區塊範圍 [start, end]
public function getPageRange(): array {
$last = $this->lastPage();
if ($last <= $this->pageRange) return [1, $last];
$half = (int)($this->pageRange / 2);
$start = max(1, $this->page - $half);
$end = min($last, $start + $this->pageRange - 1);
if ($end - $start + 1 < $this->pageRange) {
$start = max(1, $end - $this->pageRange + 1);
}
return [$start, $end];
}
// 輸出 HTML(Bootstrap 5 風格)
public function render(): string {
if ($this->lastPage() <= 1) return '';
[$start, $end] = $this->getPageRange();
$html = '';
$html .= '第 ' . $this->page . ' / ' . $last . ' 頁,共 ' . $this->total . ' 筆
';
return $html;
}
// 輸出 JSON 供 AJAX/Vue/React 使用
public function toArray(): array {
[$start, $end] = $this->getPageRange();
$pages = [];
for ($i = $start; $i <= $end; $i++) {
$pages[] = ['page' => $i, 'url' => $this->url($i), 'active' => $i === $this->page];
}
return [
'current_page' => $this->page,
'last_page' => $this->lastPage(),
'per_page' => $this->perPage,
'total' => $this->total,
'from' => $this->offset() + 1,
'to' => min($this->offset() + $this->perPage, $this->total),
'pages' => $pages,
'prev_url' => $this->page > 1 ? $this->url($this->page - 1) : null,
'next_url' => $this->page < $this->lastPage() ? $this->url($this->page + 1) : null,
];
}
}
<?php
require 'Paginator.php';
$total = 1234; // 從 COUNT(*) 取得
$page = (int)($_GET['page'] ?? 1);
$paginator = new Paginator($total, 20, $page);
// 查詢資料
$stmt = $pdo->prepare("SELECT * FROM articles ORDER BY id DESC LIMIT ?, ?");
$stmt->execute([$paginator->offset(), $paginator->limit()]);
$articles = $stmt->fetchAll();
// 輸出分頁
echo $paginator->render();
header('Content-Type: application/json');
echo json_encode([
'data' => $articles,
'pagination' => $paginator->toArray(),
]);
$paginator = new Paginator($total, 20, $page, '/article/list/page-{page}.html');