萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 數字分頁類完整實作(支援 URL 佈局、自定義樣式、AJAX 模式)

功能特性

  • 支援首頁、尾頁、上一頁、下一頁、頁碼區塊(可配置顯示頁碼數)。
  • 自動處理邊界(第一頁隱藏上一頁、最後頁隱藏下一頁)。
  • 支援任意 URL 格式(查詢字串、PATH_INFO、偽靜態)。
  • 可輸出純 HTML、JSON(AJAX)、或陣列供前端框架渲染。

核心類別代碼

<?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, ]; } }

使用範例

傳統 HTML 頁面

<?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();

API 回傳 JSON (Vue/React/AJAX)

header('Content-Type: application/json');
echo json_encode([
    'data' => $articles,
    'pagination' => $paginator->toArray(),
]);

自定義 URL 模式(偽靜態)

$paginator = new Paginator($total, 20, $page, '/article/list/page-{page}.html');
copyright © 萬盛學電腦網 all rights reserved