萬盛學電腦網

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

PHP 通用分頁類:支援靜態化 URL、AJAX 分頁、多種樣式模式

分頁是 Web 應用最常見的需求。本文提供一個高度可配置的 PHP 分頁類 Pager,支援 靜態化偽靜態 URL、無連結 AJAX 模式、多組分頁共存、自訂顯示範圍,可直接整合至任何專案。

核心類別實作

<?php
class Pager
{
    private $link = '';        // 基礎連結 (含 -p{page} 佔位符)
    private $page = 1;         // 當前頁
    private $total = 0;        // 總頁數
    private $size = 5;         // 顯示頁碼數量
    private $type = '';        // 分頁區塊識別碼 (多組分頁用)
    private $ajax = false;     // 是否 AJAX 模式

    public function __construct(array $config = [])
    {
        foreach ($config as $k => $v) {
            if (property_exists($this, $k)) $this->$k = $v;
        }
    }

    public function render(): string
    {
        if ($this->total <= 1) return '';

        $html = '<nav class="pager" aria-label="Pagination"><ul>';

        // 上一頁
        $html .= $this->page > 1
            ? $this->linkItem($this->page - 1, '« 上一頁', 'prev')
            : '<li class="disabled"><span>« 上一頁</span></li>';

        // 頁碼範圍計算
        $start = max(1, $this->page - floor($this->size / 2));
        $end   = min($this->total, $start + $this->size - 1);
        if ($end - $start + 1 < $this->size) {
            $start = max(1, $end - $this->size + 1);
        }

        // 首頁 + 省略號
        if ($start > 1) {
            $html .= $this->linkItem(1, '1', 'first');
            if ($start > 2) $html .= '<li class="ellipsis"><span>...</span></li>';
        }

        // 頁碼列表
        for ($i = $start; $i <= $end; $i++) {
            $html .= $this->linkItem($i, (string)$i, $i === $this->page ? 'current' : 'page');
        }

        // 尾頁 + 省略號
        if ($end < $this->total) {
            if ($end < $this->total - 1) $html .= '<li class="ellipsis"><span>...</span></li>';
            $html .= $this->linkItem($this->total, (string)$this->total, 'last');
        }

        // 下一頁
        $html .= $this->page < $this->total
            ? $this->linkItem($this->page + 1, '下一頁 »', 'next')
            : '<li class="disabled"><span>下一頁 »</span></li>';

        $html .= '</ul></nav>';
        return $html;
    }

    private function linkItem(int $page, string $text, string $class): string
    {
        $attrs = 'class="' . $class . '"';
        if ($this->ajax) {
            $attrs .= ' data-page="' . $page . '" data-type="' . $this->type . '"';
            $href = 'javascript:void(0)';
        } else {
            $url = preg_replace('/-p\d+/', '-p' . $page, $this->link);
            $href = htmlspecialchars($url);
        }
        return '<li><a href="' . $href . '" ' . $attrs . '>' . $text . '</a></li>';
    }

    // 設定器
    public function setLink(string $link) { $this->link = $link; return $this; }
    public function setPage(int $page) { $this->page = max(1, $page); return $this; }
    public function setTotal(int $total) { $this->total = max(0, $total); return $this; }
    public function setSize(int $size) { $this->size = max(3, $size); return $this; }
    public function setType(string $type) { $this->type = $type; return $this; }
    public function setAjax(bool $ajax) { $this->ajax = $ajax; return $this; }
}

使用範例

1. 傳統靜態化 URL 模式

<?php
// URL 格式: /article/list-cate5-p{page}.html
$pager = new Pager([
    'link'  => '/article/list-cate5-p{page}.html',
    'page'  => $_GET['page'] ?? 1,
    'total' => $totalPages,
    'size'  => 5,
]);

echo $pager->render();
?>

2. AJAX 無刷新分頁模式

<?php
$pager = new Pager([
    'link'  => '',           // 空連結觸發 AJAX 模式
    'page'  => 1,
    'total' => $totalPages,
    'type'  => 'article_list', // 區分同頁多組分頁
    'ajax'  => true,
    'size'  => 5,
]);

echo $pager->render();
?>

<script>
// 統一事件委派處理所有 AJAX 分頁
document.querySelectorAll('.pager[data-type]').forEach(nav => {
    nav.addEventListener('click', e => {
        const a = e.target.closest('a[data-page]');
        if (!a) return;
        e.preventDefault();
        const page = parseInt(a.dataset.page);
        const type = a.dataset.type;
        loadPage(type, page);
    });
});

function loadPage(type, page) {
    const container = document.querySelector(`.pager[data-type="${type}"]`).closest('.pager-container');
    container.innerHTML = '<div class="loading">載入中...</div>';
    fetch(`/api/articles?type=${type}&page=${page}`)
        .then(r => r.text())
        .then(html => container.innerHTML = html);
}
</script>

3. 同頁多組分頁 (如:文章列表 + 評論列表)

<?php
// 文章分頁
$articlePager = (new Pager())
    ->setLink('/article/list-p{page}.html')
    ->setPage($_GET['apage'] ?? 1)
    ->setTotal($articleTotalPages)
    ->setType('article');

// 評論分頁
$commentPager = (new Pager())
    ->setLink('/article/comment-aid123-p{page}.html')
    ->setPage($_GET['cpage'] ?? 1)
    ->setTotal($commentTotalPages)
    ->setType('comment');
?>

<div class="pager-container">
    <h3>文章列表</h3>
    <?= $articlePager->render() ?>
</div>

<div class="pager-container">
    <h3>評論列表</h3>
    <?= $commentPager->render() ?>
</div>

CSS 樣式建議 (Flexbox 現代佈局)

.pager ul { display: flex; gap: 4px; list-style: none; padding: 0; margin: 16px 0; flex-wrap: wrap; }
.pager a, .pager span { display: inline-flex; align-items: center; justify-content: center; min-width: 36px; height: 36px; padding: 0 10px; border: 1px solid #ddd; border-radius: 4px; text-decoration: none; color: #333; transition: all 0.2s; }
.pager a:hover { background: #f5f5f5; border-color: #007bff; color: #007bff; }
.pager .current a { background: #007bff; border-color: #007bff; color: #fff; cursor: default; }
.pager .disabled span { color: #999; cursor: not-allowed; }
.pager .ellipsis span { border-color: transparent; cursor: default; }
.pager .loading { padding: 20px; text-align: center; color: #666; }

SEO 與無障礙建議

  • 靜態化 URL 使用 rel="prev/next" (舊標準) 或 link rel="prev/next" 標頭
  • AJAX 分頁配合 History.pushState 更新 URL,保持可分享、可收藏
  • 提供 aria-label、role="navigation" 輔助閱讀器
  • 首頁/尾頁連結加 rel="canonical" 指向標準 URL
copyright © 萬盛學電腦網 all rights reserved