為什麼需要規範?
- 降低認知負擔:統一風格讓團隊專注業務邏輯
- 減少無意義衝突:格式差異不再產生 Git diff 雜訊
- 啟用靜態分析:型別宣告讓 PHPStan/Psalm 發現潛在 Bug
- 自動化品質把關:CI 阻擋不合規程式碼合併
PSR-12 核心規範 (PHP-FIG 標準)
<?php
declare(strict_types=1); // 嚴格模式,檔案最頂端
namespace App\Service;
use App\Dto\UserDto;
use App\Exception\UserNotFoundException;
use function count;
use const PHP_VERSION_ID;
class UserService implements UserServiceInterface
{
public function __construct(
private readonly UserRepositoryInterface $repository,
private readonly LoggerInterface $logger,
) {}
public function findById(int $id): ?UserDto
{
if ($id <= 0) {
throw new InvalidArgumentException('ID 必須為正整數');
}
$user = $this->repository->find($id);
if ($user === null) {
$this->logger->warning('用戶不存在', ['id' => $id]);
return null;
}
return UserDto::fromEntity($user);
}
/** @return array */
public function findActive(int $limit = 20, int $offset = 0): array
{
if ($limit > 100) {
$limit = 100; // 防禦性程式設計
}
return array_map(
UserDto::fromEntity(...),
$this->repository->findActive($limit, $offset)
);
}
}
關鍵規範重點
- 縮排:4 空格,不可用 Tab
- 行長度:軟限制 120 字元,硬限制無 (但建議 < 120)
- 命名空間/Use 宣告:分組 (PHP 內建、第三方、專案內部),字母序
- 類別/方法/屬性:StudlyCaps / camelCase / camelCase
- 型別宣告:嚴格模式、回傳型別、屬性型別 (PHP 7.4+)、readonly (PHP 8.1+)
- 控制結構:
if ( 空格、大括號同行、else/elseif 换行
- 嚴格比較:預設用
=== !==
現代工具鏈整合
1. 程式碼風格自動修正:PHP-CS-Fixer / Pint
# composer require --dev friendsofphp/php-cs-fixer laravel/pint
# .php-cs-fixer.dist.php
return (new PhpCsFixer\Config())
->setRules(['@PSR12' => true, 'strict_param' => true])
->setFinder(PhpCsFixer\Finder::create()->in(__DIR__ . '/src'));
// 執行
vendor/bin/php-cs-fixer fix --diff
# 或 Laravel Pint (零設定)
vendor/bin/pint
2. 靜態分析:PHPStan / Psalm
# composer require --dev phpstan/phpstan
# phpstan.neon
parameters:
level: 5 # 0-9, 建議從 5 開始
paths:
- src
excludePaths:
- src/legacy
checkMissingIterableValueType: true
# 執行
vendor/bin/phpstan analyse --memory-limit=512M
3. 型別檢查:PHPStan + PHPUnit 基準測試
# 產生基準線 (允許現有錯誤暫時存在)
vendor/bin/phpstan analyse --generate-baseline
# 後續新代碼必須通過,舊錯誤逐步修復
4. Git Hooks:Husky / pre-commit
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: php-cs-fixer
name: PHP CS Fixer
entry: vendor/bin/php-cs-fixer fix --diff --dry-run
language: system
types: [php]
- id: phpstan
name: PHPStan
entry: vendor/bin/phpstan analyse --no-progress
language: system
types: [php]
# 可設定 stages: [commit] 只在 commit 時跑
5. CI 整合
# .github/workflows/ci.yml
jobs:
static-analysis:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
with: { php-version: '8.2', extensions: mbstring, xml, curl }
- run: composer install --prefer-dist --no-progress
- run: vendor/bin/php-cs-fixer fix --diff --dry-run
- run: vendor/bin/phpstan analyse --no-progress
專案結構建議
src/
├── Domain/ # 核心業務邏輯、實體、值物件、介面
├── Application/ # 用例、命令、查詢、DTO
├── Infrastructure/ # 資料庫、外部 API、框架整合
└── Presentation/ # Controller、Command、Event Listener
tests/
├── Unit/
├── Integration/
└── E2E/
原文片段現代化重寫對比
| 原文 (2009 風格) | 現代重寫 (PHP 8.2+) |
include("Inc/Conn.php") | Composer 自動載入、DI 容器注入 |
Get_value('id',0) | Request DTO + 驗證器 |
mysql_query() | PDO + 預處理語句 / ORM (Eloquent/Doctrine) |
ShowMsg('{...}') | JsonResponse + Exception Handler |
| 無型別宣告 | 嚴格型別、回傳型別、屬性型別 |