php-best-practices

php-best-practices

PHP 8.x 現代模式、PSR 標準與 SOLID 原則。用於審查 PHP 程式碼、檢查型別安全、稽核程式碼品質,或確保 PHP 最佳實務。觸發詞為「review PHP」、「check PHP code」、「audit PHP」或「PHP best practices」。

59星標
9分支
更新於 2026/5/16
SKILL.md
唯讀
名稱
php-best-practices
描述

PHP 8.x 現代模式、PSR 標準與 SOLID 原則。用於審查 PHP 程式碼、檢查型別安全、稽核程式碼品質,或確保 PHP 最佳實務。觸發詞為「review PHP」、「check PHP code」、「audit PHP」或「PHP best practices」。

PHP 最佳實務

現代 PHP 8.x 模式、PSR 標準、型別系統最佳實務與 SOLID 原則。包含 51 條規則,用於撰寫乾淨、可維護的 PHP 程式碼。

步驟 1:偵測 PHP 版本

在提供任何建議前,務必檢查專案的 PHP 版本。 不同版本(8.0 - 8.5)的功能差異很大。切勿建議專案版本中不存在的語法。

檢查 composer.json 中的 PHP 版本需求:

{ "require": { "php": "^8.1" } }   // -> 適用 8.1 及以下規則
{ "require": { "php": "^8.3" } }   // -> 適用 8.3 及以下規則
{ "require": { "php": ">=8.4" } }  // -> 適用 8.4 及以下規則

同時檢查執行環境版本:

php -v   # 例如 PHP 8.3.12

各版本功能可用性

功能 版本 規則前綴
Union types、match、nullsafe、named args、constructor promotion、attributes 8.0+ type-modern-
Enums、readonly properties、intersection types、first-class callables、never、fibers 8.1+ modern-
Readonly classes、DNF types、true/false/null 獨立型別 8.2+ modern-
Typed class constants、#[\Override]json_validate() 8.3+ modern-
Property hooks、asymmetric visibility、#[\Deprecated]new 不需括號 8.4+ modern-
Pipe operator ` >` 8.5+

僅建議偵測版本中可用的功能。 若使用者詢問升級或新功能,請說明各版本新增了哪些功能。

適用時機

在以下情況參考這些準則:

  • 撰寫或審查 PHP 程式碼
  • 實作類別與介面
  • 使用 PHP 8.x 現代功能
  • 確保型別安全
  • 遵循 PSR 標準
  • 套用設計模式

依優先順序的規則分類

優先順序 分類 影響 前綴 規則數
1 型別系統 嚴重 type- 9
2 現代 PHP 功能 嚴重 modern- 16
3 PSR 標準 psr- 6
4 SOLID 原則 solid- 5
5 錯誤處理 error- 5
6 效能 perf- 5
7 安全性 嚴重 sec- 5

快速參考

1. 型別系統(嚴重)— 9 條規則

  • type-strict-mode - 在每個檔案中宣告嚴格型別
  • type-return-types - 一律宣告回傳型別
  • type-parameter-types - 為所有參數加上型別
  • type-property-types - 為類別屬性加上型別
  • type-union-types - 有效使用 union types
  • type-intersection-types - 使用 intersection types
  • type-nullable-types - 正確處理 nullable types
  • type-void-never - 使用 void/never 作為適當的回傳型別
  • type-mixed-avoid - 盡量避免使用 mixed 型別

2. 現代 PHP 功能(嚴重)— 16 條規則

8.0+:

  • modern-constructor-promotion - 建構子屬性提升
  • modern-match-expression - 使用 match 取代 switch
  • modern-named-arguments - 使用具名引數提升可讀性
  • modern-nullsafe-operator - Nullsafe 運算子 (?->)
  • modern-attributes - 使用屬性(Attributes)作為中繼資料

8.1+:

  • modern-enums - 使用 Enum 取代常數
  • modern-enums-methods - 帶方法與介面的 Enum
  • modern-readonly-properties - 使用 readonly 處理不可變資料
  • modern-first-class-callables - First-class callable 語法
  • modern-arrow-functions - 箭頭函式(7.4+,與 8.1 功能搭配良好)

8.2+:

  • modern-readonly-classes - Readonly 類別

8.3+:

  • modern-typed-constants - 型別化類別常數(const string NAME = 'foo'
  • modern-override-attribute - 使用 #[\Override] 捕捉父類別方法拼寫錯誤

8.4+:

  • modern-property-hooks - 使用屬性鉤子取代 getter/setter
  • modern-asymmetric-visibility - 使用 public private(set) 控制存取

8.5+:

  • modern-pipe-operator - 使用管道運算子(|>)進行函數式串接

3. PSR 標準(高)— 6 條規則

  • psr-4-autoloading - 遵循 PSR-4 自動載入
  • psr-12-coding-style - 遵循 PSR-12 編碼風格
  • psr-naming-classes - 類別命名慣例
  • psr-naming-methods - 方法命名慣例
  • psr-file-structure - 每個檔案一個類別
  • psr-namespace-usage - 正確使用命名空間

4. SOLID 原則(高)— 5 條規則

  • solid-srp - 單一職責:只有一個變更理由
  • solid-ocp - 開放/封閉:擴充而非修改
  • solid-lsp - 里氏替換:子型別必須可替換
  • solid-isp - 介面隔離:小而專注的介面
  • solid-dip - 依賴反轉:依賴抽象

5. 錯誤處理(高)— 5 條規則

  • error-custom-exceptions - 為不同錯誤建立特定例外
  • error-exception-hierarchy - 將例外組織成有意義的階層
  • error-try-catch-specific - 捕捉特定例外,而非通用的 \Exception
  • error-finally-cleanup - 使用 finally 確保資源清理
  • error-never-suppress - 絕不使用 @ 錯誤抑制運算子

6. 效能(中)— 5 條規則

  • perf-avoid-globals - 避免全域變數,使用依賴注入
  • perf-lazy-loading - 延遲昂貴操作直到需要時
  • perf-array-functions - 使用原生陣列函式取代手動迴圈
  • perf-string-functions - 使用原生字串函式取代正規表達式
  • perf-generators - 對大型資料集使用生成器

7. 安全性(嚴重)— 5 條規則

  • sec-input-validation - 驗證並清理所有外部輸入
  • sec-output-escaping - 依內容(HTML、JS、URL)跳脫輸出
  • sec-password-hashing - 使用 password_hash/verify,絕不使用 MD5/SHA1
  • sec-sql-prepared - 所有 SQL 查詢使用預備陳述式
  • sec-file-uploads - 驗證檔案類型、大小、名稱;儲存於網頁根目錄之外

基本準則

如需詳細範例與說明,請參閱規則檔案:

關鍵模式(快速參考)

<?php
declare(strict_types=1);

// 8.0+ 建構子提升 + readonly(8.1+)
class User
{
    public function __construct(
        public readonly string $id,
        private string $email,
    ) {}
}

// 8.1+ 帶方法的 Enum
enum Status: string
{
    case Active = 'active';
    case Inactive = 'inactive';

    public function label(): string
    {
        return match($this) {
            self::Active => 'Active',
            self::Inactive => 'Inactive',
        };
    }
}

// 8.0+ Match 表達式
$result = match($status) {
    'pending' => 'Waiting',
    'active' => 'Running',
    default => 'Unknown',
};

// 8.0+ Nullsafe 運算子
$country = $user?->getAddress()?->getCountry();

// 8.3+ 型別化類別常數 + #[\Override]
class PaymentService extends BaseService
{
    public const string GATEWAY = 'stripe';

    #[\Override]
    public function process(): void { /* ... */ }
}

// 8.4+ 屬性鉤子 + 不對稱可見性
class Product
{
    public string $name { set => trim($value); }
    public private(set) float $price;
}

// 8.5+ 管道運算子
$result = $input
    |> trim(...)
    |> strtolower(...)
    |> htmlspecialchars(...);

輸出格式

稽核程式碼時,請以下列格式輸出發現:

file:line - [category] 問題描述

範例:

src/Services/UserService.php:15 - [type] 缺少回傳型別宣告
src/Models/Order.php:42 - [modern] 使用 match 表達式取代 switch
src/Controllers/ApiController.php:28 - [solid] 類別有多重職責

使用方式

閱讀個別規則檔案以取得詳細說明:

rules/modern-constructor-promotion.md
rules/type-strict-mode.md
rules/solid-srp.md