萬盛學電腦網

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

PHP 實現麵包屑導航(欄目導航)的通用類與模板輸出

需求分析

根據當前請求 URI 自動生成層級導航,如:首頁 > 服務 > 家教中心 > 詳細頁。需支援自定義欄目名稱映射、URL 構建、當前頁高亮。

核心類實現

<?php
class Breadcrumb {
    private array $labelMap = [];
    private string $separator = ' > ';
    private string $homeLabel = '首頁';
    private string $homeUrl = '/';

    public function __construct(array $labelMap = [], string $separator = ' > ') {
        $this->labelMap = $labelMap;
        $this->separator = $separator;
    }

    public function setHome(string $label, string $url = '/'): self {
        $this->homeLabel = $label;
        $this->homeUrl = $url;
        return $this;
    }

    public function render(): string {
        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $uri = rtrim($uri, '/');
        if ($uri === '') $uri = '/';

        $segments = explode('/', trim($uri, '/'));
        $html = '<nav aria-label="breadcrumb"><ol class="breadcrumb">';
        $html .= '<li class="breadcrumb-item"><a href="' . $this->homeUrl . '">' . $this->homeLabel . '</a></li>';

        $buildPath = '';
        foreach ($segments as $seg) {
            $buildPath .= '/' . $seg;
            $label = $this->labelMap[$seg] ?? ucfirst($seg);
            $isLast = ($seg === end($segments));
            if ($isLast) {
                $html .= '<li class="breadcrumb-item active" aria-current="page">' . $label . '</li>';
            } else {
                $html .= '<li class="breadcrumb-item"><a href="' . $buildPath . '">' . $label . '</a></li>';
            }
        }
        $html .= '</ol></nav>';
        return $html;
    }
}

使用示例

<?php
require 'Breadcrumb.php';

$map = [
    'service' => '有償服務',
    'teach' => '家教中心',
    'union' => '校園服務聯盟',
    'job' => '學生兼職',
    'free' => '信息庫',
];

$breadcrumb = new Breadcrumb($map, ' > ');
$breadcrumb->setHome('首頁', '/index.php');

echo $breadcrumb->render();

輸出 HTML 結構(Bootstrap 5 風格)

<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="/index.php">首頁</a></li>
    <li class="breadcrumb-item"><a href="/service">有償服務</a></li>
    <li class="breadcrumb-item"><a href="/service/teach">家教中心</a></li>
    <li class="breadcrumb-item active" aria-current="page">詳細頁</li>
  </ol>
</nav>

進階擴展

  • 緩存:對靜態欄目結構緩存渲染結果,減少字符串操作開銷。
  • 數據庫驅動:從 categories 表讀取 slug、name、parent_id 動態構建映射。
  • 多語言:$labelMap 改為 ['en' => [...], 'zh-Hant' => [...]],根據語言切換。
  • Schema.org Microdata:加入 itemprop="itemListElement" 結構化數據,利於 SEO。
copyright © 萬盛學電腦網 all rights reserved