PHP 怎么PHP 合规即代码

wen PHP项目 2

本文目录导读:

PHP 怎么PHP 合规即代码

  1. 遵循PSR标准
  2. 命名规范
  3. 安全合规编码
  4. 代码组织规范
  5. 使用工具自动检查
  6. 推荐的编码规范检查清单
  7. 推荐配置

我来详细解答PHP代码合规(即代码规范)的问题。

遵循PSR标准

PHP-FIG(PHP Framework Interop Group)制定了PSR标准,最常用的是:

PSR-1:基础编码规范

<?php
// 1. 文件使用 <?php 或 <?= 标签
// 2. 文件必须不含BOM的UTF-8编码
// 3. 命名空间和类必须使用自动加载
namespace App\Models;
class UserController
{
    // 4. 类名使用首字母大写的驼峰式
    // 5. 常量全部大写,下划线分隔
    const MAX_LOGIN_ATTEMPTS = 5;
    // 6. 方法名使用首字母小写的驼峰式
    public function getUserProfile()
    {
    }
}

PSR-2:编码风格规范

<?php
namespace App\Services;
use App\Models\User;
use App\Exceptions\UserException;
class OrderService
{
    private $user;
    // 1. 花括号另起一行
    public function processOrder(array $items, $userId)
    {
        // 2. 控制结构花括号在同一行
        if (empty($items)) {
            throw new UserException('订单不能为空');
        }
        // 3. 4个空格缩进,不要用Tab
        foreach ($items as $item) {
            $this->validateItem($item);
        }
        return true;
    }
    // 4. 方法间空一行
    private function validateItem($item)
    {
        return isset($item['id']) && $item['price'] > 0;
    }
}

命名规范

<?php
// 类名:大驼峰
class DatabaseConnection {}
// 接口名:大驼峰 + Interface后缀
interface CacheInterface {}
// 方法名:小驼峰
public function getUserById($id) {}
// 变量名:小驼峰
$userName = '张三';
// 常量:全部大写
define('MAX_RETRY_COUNT', 3);
// 私有属性:下划线开头(可选)
private $_dbConnection;

安全合规编码

<?php
// 1. SQL注入防护 - 使用预处理语句
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
// 2. XSS防护 - 输出转义
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
// 3. CSRF防护 - 使用Token
session_start();
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    die('CSRF验证失败');
}
// 4. 输入验证
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
if (!$email) {
    throw new InvalidArgumentException('无效的邮箱地址');
}

代码组织规范

<?php
/**
 * @file UserService.php
 * @brief 用户服务层
 * @author 开发者
 * @date 2024-01-01
 */
namespace App\Services;
use App\Models\User;
use App\Repositories\UserRepository;
class UserService
{
    private $userRepo;
    /**
     * 依赖注入
     * @param UserRepository $userRepo
     */
    public function __construct(UserRepository $userRepo)
    {
        $this->userRepo = $userRepo;
    }
    /**
     * 创建用户(单一职责原则)
     * @param array $data
     * @return User
     * @throws ValidationException
     */
    public function createUser(array $data): User
    {
        $this->validateUserData($data);
        $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT);
        $data['created_at'] = date('Y-m-d H:i:s');
        return $this->userRepo->save($data);
    }
    // 私有方法辅助主逻辑
    private function validateUserData(array $data): void
    {
        $required = ['name', 'email', 'password'];
        foreach ($required as $field) {
            if (empty($data[$field])) {
                throw new ValidationException("缺少必要字段: {$field}");
            }
        }
    }
}

使用工具自动检查

# 1. PHP CodeSniffer - 检查代码规范
phpcs --standard=PSR2 app/
# 2. PHP CS Fixer - 自动修复格式
php-cs-fixer fix app/ --rules=@PSR2
# 3. PHPStan - 静态分析
phpstan analyse app/ --level=max

推荐的编码规范检查清单

<?php
// ✅ 正确做法
class UserManager {
    public function findUser(int $id): ?User
    {
        // 类型声明
    }
}
// ❌ 错误做法
class usermanager {
    public function find_user($id)
    {
        // 不规范的命名和类型
    }
}
// ✅ 正确的注释
/**
 * 获取用户信息
 *
 * @param int $userId 用户ID
 * @return array 用户信息数组
 * @throws UserNotFoundException
 */
// ❌ 错误的注释
// 获取用户信息
// @param $id 用户ID

推荐配置

composer.json 中添加:

{
    "require-dev": {
        "squizlabs/php_codesniffer": "^3.7",
        "friendsofphp/php-cs-fixer": "^3.0",
        "phpstan/phpstan": "^1.0"
    },
    "scripts": {
        "check": "phpcs --standard=PSR12 src/",
        "fix": "php-cs-fixer fix src/"
    }
}

这样既能保证代码规范,又能提高代码质量和安全性。

抱歉,评论功能暂时关闭!