首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 程式設計最佳實踐指南(上):架構分層、依賴注入與錯誤處理

     編輯:PHP 相關知識

構建可維護、可測試、可擴展的 PHP 專案架構

1. 分層架構 (Layered Architecture)

src/
├── Domain/           # 核心業務邏輯,零外部依賴
│   ├── Entity/       # 富領域模型
│   ├── Repository/   # 介面定義
│   └── Service/      # 領域服務
├── Application/      # 用例協調器
│   ├── Command/      # 寫操作
│   └── Query/        # 讀操作 (CQRS)
├── Infrastructure/   # 技術實作
│   ├── Persistence/  # Doctrine/PDO Repository 實作
│   ├── Http/         # Controller、Middleware
│   └── Messaging/    # Queue、Event Bus
└── Interface/        # 進程入口 (Console, Web, gRPC)

依賴方向:Interface → Application → Domain ← Infrastructure (依賴倒置)。

2. 依賴注入容器 (DI Container)

<?php
// 使用 PHP-DI 定義
return [
    UserRepositoryInterface::class => \DI\autowire(UserRepositoryDoctrine::class),
    UserService::class => \DI\autowire()->constructorParameter('mailer', \DI\get(MailerInterface::class)),
    // Controller 自動注入
];
// Controller
class UserController {
    public function __construct(private UserService $service) {}
    public function show(int $id): JsonResponse {
        return new JsonResponse($this->service->getUser($id));
    }
}
?>

3. 例外處理 vs 錯誤碼

  • 例外:不可預期、必須中斷流程的錯誤 (資料庫連線失敗、第三方 API 異常)。建立領域例外 class UserNotFoundException extends DomainException。
  • Result 型別 / 錯誤碼:可預期、業務規則驗證失敗 (輸入無效、庫存不足)。回傳 Result::success($data) / Result::failure($code, $message)。
  • 全域例外處理器:將例外轉為統一 HTTP 回應 (JSON API: {"error": {"code": "...", "message": "..."}})。

4. 單一職責原則 (SRP) 落地

  • Controller 僅負責 HTTP 協議轉換 (請求解析、回應序列化)。
  • Service 單一業務用例,不處理 HTTP、DB 細節。
  • Repository 單一實體持久化操作。

5. 配置管理

  • 環境變數 (.env) 管理敏感/環境差異配置 (DB 憑證、API Key)。
  • 結構化配置檔 (config/packages/*.php) 管理應用行為參數。
  • 使用 vlucas/phpdotenv + symfony/config 驗證配置完整性。

遵循這些實踐,專案將具備清晰邊界、低耦合、高可測試性,支撐長期演進。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved