大型 PHP 專案 (百萬行代碼、多人團隊、長週期迭代) 的核心挑戰在於**複雜度控制**、**一致性保障**、**可維護性**與**擴展性**。本文提煉實戰經驗,覆蓋變量、函數/類、註釋、工具、數據庫、架構六大維度。
config/ 目錄下環境區分文件 (config/database.php, config/services.php),**禁用全局變量/常量散落**。使用 config('database.host') 訪問 (Laravel) 或 $container->get('config')['db']['host'] (PSR-11)。camelCase ($userName, $maxRetryCount)。UPPER_SNAKE_CASE (DB_HOST, MAX_UPLOAD_SIZE)。$i, $k, $v, $item 等慣用短名。$data, $arr, $tmp — 除非極局部)。declare(strict_types=1); 文件首行。function calculateTotal(Order $order, int $quantity, float $discount = 0.0): float。private string $name; (PHP 7.4+)。unset() 釋放大數據變量 (數組、對象) 內存。calculateTax() 只算稅,不查庫、不寫日誌。副作用隔離。function shipOrder(ShippingOrderDTO $dto): TrackingNumber。setter 注入可選依賴。**絕不在類內 new 依賴** (除非 Value Object/Entity)。使用 PHP-DI、Symfony DI、Laravel 容器。interface PaymentGateway { charge(Money $amount): ChargeResult; },實現類依賴介面。便於測試 Mock、替換實現 (Stripe/PayPal/沙箱)。class Order { use HasStatusTrait; use HasPricingTrait; } (Trait 組合) 或策略模式 $order->setPricingStrategy(new VIPStrategy())。繼承層級 ≤ 2。class Money { private int $cents; private string $currency; public function __construct(...) {} public function add(Money $other): self { ... } } — 無 setter、運算返回新實例、線程安全、可做鍵。$order->place()),而非 Service 類流程腳本。Service 只協調事務、外部調用。/** 計算訂單總價(含稅) * @param Order $order 已驗證的訂單實體 * @param float $taxRate 稅率(0-1) * @return Money 總價 * @throws InvalidArgumentException 稅率無效 */function sendEmail(string $to, string $subject, string $body): bool 無需 @param string $to。// 按照「先到先得、VIP優先、大額優先」三級排序規則。phpDocumentor、swagger-php (OpenAPI)、Scribe (Laravel)。CI 中強制生成、驗證無斷鏈。docs/adr/,不可變歷史。.idea/.vscode 配置 (代碼風格、檢查器、運行配置) 納入版控。PHP-CS-Fixer (推薦 @PSR12 + 風險規則) + PHP_CodeSniffer (CI 門禁)。pre-commit 鉤子本地攔截。PHPUnit + Pest (更優雅)。核心領域模型覆蓋率 ≥ 90%,整體 ≥ 70%。infection 變異測試驗證斷言質量。composer audit / Snyk / GitHub Dependabot 自動修復。phinx/Laravel Migrations/Doctrine Migrations)。**禁用手動 ALTER TABLE**。版本控制、可回滾、可審計。snake_case 複數 (order_items)、主鍵 id (BIGINT UNSIGNED)、外鍵 {singular}_id (user_id)、時間戳 created_at/updated_at (TIMESTAMP DEFAULT CURRENT_TIMESTAMP)、軟刪除 deleted_at (NULLABLE)。EXPLAIN 驗證慢查詢、避免過度索引。hasMany, belongsTo, belongsToMany)。with('relation') (Eager Loading) / loadMissing()。insert()/upsert()/chunkById()。DB::transaction(fn() => ...)。read/write 連接。強一致性場景 (寫後讀) 強制主庫。Controller (HTTP 處理、驗證、響應) → Action/UseCase (單一業務用例編排) → Service (跨聚合根邏輯、外部集成) → Repository (數據持久化抽象) → Model/Entity (領域核心邏輯、狀態、不變量)。Modules/User, Modules/Order, Modules/Payment),各模塊內部高內聚、通過定義良好的介面 (Service Contract/Event) 通信。**避免大泥球**。EventDispatcher 分發領域事件 (OrderPlaced, PaymentReceived)。監聽器異步處理 (發郵件、更新搜索索引、同步 ERP、風控)。使用 Stamped/Symfony Messenger/Laravel Events/Queues。/api/v1/)、統一錯誤格式 (RFC 7807 Problem Details)、速率限制、冪等鍵。大型 PHP 專案成功的關鍵:**嚴格的工程化規範** (類型、靜態分析、CI/CD) + **清晰的架構邊界** (分層、模組、DDD) + **自動化質量門禁** + **團隊共識與持續重構文化**。工具鏈 (PHPStan, PHP-CS-Fixer, PHPUnit, Rector, PHP-DI) 讓規範落地。從「能跑」到「好維護、好擴展、好測試、好交付」,是職業開發者的必修課。