萬盛學電腦網

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

PHP 模組化設計:include/require 差異、模組劃分策略與實戰架構

include vs require 核心差異

特性includerequire
檔案不存在發出 Warning,腳本繼續執行發出 Fatal Error,腳本終止
解析時機**執行時** 遇到該行才編譯載入**編譯期** 即載入 (PHP 4) / 執行前載入 (PHP 5+)
條件載入支援 if (...) include 'a.php';無條件載入,即使在 if(false) 區塊
效能略慢 (執行時決定)略快 (預先編譯)
回傳值可接收被載入檔案的 return 值同

現代建議 (PHP 5.3+):幾乎永遠用 require_once。自動載入器 (PSR-4/Composer) 已取代手動 include/require,唯有「條件載入不同模板」等極少數場景仍用 include。

為何要模組化?

  • DRY (Don't Repeat Yourself):導航列、頁尾、資料庫連線、共用函數只寫一次。
  • 關注點分離:業務邏輯、資料存取、呈現邏輯分層。
  • 團隊協作:不同人負責不同模組,減少衝突。
  • 可測試性:單元測試可針對單一模組 Mock 依賴。

建議的模組劃分 (參考經典四層架構)

project/
├── public/              # 公開入口 (index.php, assets/)
├── src/
│   ├── Core/            # 核心基礎類 (Config, Database, Router, Container)
│   ├── Domain/          # 業務領域模型 (Entity, Repository Interface, Service)
│   │   ├── User/
│   │   ├── Product/
│   │   └── Order/
│   ├── Infrastructure/  # 基礎設施實作 (PDO Repository, Redis Cache, Mailer)
│   └── Presentation/    # 呈現層 (Controller, View, Middleware, FormRequest)
├── templates/           # Blade/Twig/Smarty 模板
├── tests/               # 單元/整合測試
├── vendor/              # Composer 依賴
├── composer.json
└── .env

實戰:共用版面模組化範例 (傳統 PHP 寫法)

<?php
// layout.php - 統一版面
$title = $title ?? 'My Site';
$content = $content ?? '';
?>
<!DOCTYPE html>
<html>
<head>
    <title><?= htmlspecialchars($title) ?></title>
    <link rel="stylesheet" href="/css/app.css">
</head>
<body>
    <header><?php include 'partials/nav.php'; ?></header>
    <main><?= $content ?></main>
    <footer><?php include 'partials/footer.php'; ?></footer>
</body>
</html>
<?php
// article.php - 內容頁
require_once __DIR__ . '/bootstrap.php'; // 載入自動載入、DB、Session

$article = $articleRepository->findBySlug($_GET['slug'] ?? '');
if (!$article) { http_response_code(404); include '404.php'; exit; }

$title = $article->title;
ob_start();
include 'templates/article_detail.php';
$content = ob_get_clean();

include 'layout.php';

自動載入:徹底告別手動 require

// composer.json
{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}
// 執行 composer dump-autoload
// 之後直接 use App\Domain\User\UserService; 即可使用,零 require。

結語

模組化不是把檔案切碎,而是**依業務邊界劃分邏輯單元**,配合 Composer 自動載入、依賴注入容器、介面導向程式設計,構建高內聚、低耦合、可測試、可擴展的系統。從 include 'config.php' 開始,走向 use App\Core\Config;,是每個 PHP 開發者必經的架構演進之路。

copyright © 萬盛學電腦網 all rights reserved