萬盛學電腦網

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

PHP 程式碼規範化實作範本:類別結構、註解與風格標準

標準檔案結構範本

<?php
/**
 * @file       UserService.php
 * @brief      使用者服務層
 * @author     Dev Team 
 * @version    2.3.1
 * @date       2024-01-15
 * @license    MIT
 */

declare(strict_types=1);

namespace App\Services;

use App\Entities\User;
use App\Repositories\UserRepository;
use App\Exceptions\UserNotFoundException;
use Psr\Log\LoggerInterface;

/**
 * 使用者服務類別
 *
 * 處理使用者註冊、認證、資料更新等業務邏輯
 *
 * @package App\Services
 * @since   1.0.0
 */
class UserService {
    /** @var UserRepository 使用者資料存取層 */
    private UserRepository $userRepo;

    /** @var LoggerInterface 日誌記錄器 */
    private LoggerInterface $logger;

    /**
     * 建構子
     *
     * @param UserRepository   $userRepo 使用者倉儲
     * @param LoggerInterface  $logger   日誌介面
     */
    public function __construct(UserRepository $userRepo, LoggerInterface $logger) {
        $this->userRepo = $userRepo;
        $this->logger   = $logger;
    }

    /**
     * 註冊新使用者
     *
     * @param  array  $data  使用者資料 ['email'=>..., 'password'=>..., 'name'=>...]
     * @return User          建立的使用者實體
     * @throws \InvalidArgumentException 資料驗證失敗
     * @throws \RuntimeException         系統錯誤
     */
    public function register(array $data): User {
        // 1. 驗證輸入
        $this->validateRegistrationData($data);

        // 2. 檢查信箱唯一性
        if ($this->userRepo->existsByEmail($data['email'])) {
            throw new \InvalidArgumentException('Email 已被註冊');
        }

        // 3. 建立實體並持久化
        $user = new User(
            email: $data['email'],
            passwordHash: password_hash($data['password'], PASSWORD_ARGON2ID),
            name: $data['name'],
        );
        $this->userRepo->save($user);

        $this->logger->info('使用者註冊成功', ['user_id' => $user->getId()]);
        return $user;
    }

    /**
     * 依 ID 取得使用者
     *
     * @param  int  $id  使用者 ID
     * @return User
     * @throws UserNotFoundException 找不到使用者
     */
    public function findById(int $id): User {
        $user = $this->userRepo->find($id);
        if (!$user) {
            throw new UserNotFoundException("使用者 ID {$id} 不存在");
        }
        return $user;
    }

    /**
     * 更新使用者基本資料
     *
     * @param  int   $id   使用者 ID
     * @param  array $data 可更新欄位 ['name', 'avatar']
     * @return User
     */
    public function updateProfile(int $id, array $data): User {
        $user = $this->findById($id);
        
        // 僅允許更新白名單欄位
        $allowed = ['name', 'avatar', 'bio'];
        foreach ($data as $key => $value) {
            if (in_array($key, $allowed, true)) {
                $user->{"set" . ucfirst($key)}($value);
            }
        }
        
        $this->userRepo->save($user);
        return $user;
    }

    /**
     * 驗證註冊資料
     *
     * @param  array $data
     * @return void
     * @throws \InvalidArgumentException
     */
    private function validateRegistrationData(array $data): void {
        $errors = [];
        
        if (empty($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'Email 格式錯誤';
        }
        if (empty($data['password']) || strlen($data['password']) < 8) {
            $errors[] = '密碼長度至少 8 碼';
        }
        if (empty($data['name']) || mb_strlen($data['name']) > 50) {
            $errors[] = '名稱長度 1-50 字元';
        }
        
        if ($errors) {
            throw new \InvalidArgumentException(implode('; ', $errors));
        }
    }
}
?>

規範化關鍵要素

項目標準
嚴格模式declare(strict_types=1); 檔案第一行
命名空間PSR-4 對應目錄結構
引入順序外部套件 → 內部專案 → 相對引入
類別/介面/特徵StudlyCase,單檔一類別
方法/屬性camelCase,可見性關鍵字前置
常數UPPER_SNAKE_CASE
PHPDoc所有 public/protected 成員完整標註
型別宣告參數、回傳、屬性皆標註型別
錯誤處理具體例外類別,避免通用 Exception
單一職責私有方法拆解細節邏輯

自動化檢查流程

# composer.json scripts 區段
"scripts": {
    "cs-check": "phpcs --standard=PSR12 src/",
    "cs-fix": "php-cs-fixer fix src/ --rules=@PSR12",
    "stan": "phpstan analyse src/ --level=5",
    "psalm": "psalm --show-info=false",
    "test": "phpunit",
    "ci": ["@cs-check", "@stan", "@psalm", "@test"]
}

Git Hooks 整合

# .git/hooks/pre-commit
#!/bin/sh
composer cs-fix
composer stan
composer test
# 失敗則阻止 commit

以此範本為基準,配合自動化工具鏈,可確保團隊程式碼風格一致、型別安全、文件同步,大幅降低維護成本。

copyright © 萬盛學電腦網 all rights reserved