php-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

PHP Best Practices

PHP最佳实践

Modern PHP 8.x patterns, PSR standards, type system best practices, and SOLID principles. Contains 45+ rules for writing clean, maintainable PHP code.
适用于现代PHP 8.x的开发模式、PSR标准、类型系统最佳实践及SOLID原则。包含45+条编写整洁、可维护PHP代码的规则。

When to Apply

适用场景

Reference these guidelines when:
  • Writing or reviewing PHP code
  • Implementing classes and interfaces
  • Using PHP 8.x modern features
  • Ensuring type safety
  • Following PSR standards
  • Applying design patterns
在以下场景中可参考本指南:
  • 编写或评审PHP代码
  • 实现类与接口
  • 使用PHP 8.x的现代特性
  • 确保类型安全
  • 遵循PSR标准
  • 应用设计模式

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Type SystemCRITICAL
type-
2Modern FeaturesCRITICAL
modern-
3PSR StandardsHIGH
psr-
4SOLID PrinciplesHIGH
solid-
5Error HandlingHIGH
error-
6PerformanceMEDIUM
perf-
7SecurityCRITICAL
sec-
优先级类别影响程度前缀
1类型系统关键
type-
2现代特性关键
modern-
3PSR标准
psr-
4SOLID原则
solid-
5错误处理
error-
6性能优化
perf-
7安全防护关键
sec-

Quick Reference

快速参考

1. Type System (CRITICAL)

1. 类型系统(关键)

  • type-strict-mode
    - Declare strict types
  • type-return-types
    - Always declare return types
  • type-parameter-types
    - Type all parameters
  • type-property-types
    - Type class properties
  • type-union-types
    - Use union types effectively
  • type-intersection-types
    - Use intersection types
  • type-nullable
    - Handle nullable types properly
  • type-mixed-avoid
    - Avoid mixed type when possible
  • type-void-return
    - Use void for no-return methods
  • type-never-return
    - Use never for non-returning functions
  • type-strict-mode
    - 声明严格类型
  • type-return-types
    - 始终声明返回类型
  • type-parameter-types
    - 为所有参数指定类型
  • type-property-types
    - 为类属性指定类型
  • type-union-types
    - 有效使用联合类型
  • type-intersection-types
    - 使用交叉类型
  • type-nullable
    - 正确处理可空类型
  • type-mixed-avoid
    - 尽可能避免使用mixed类型
  • type-void-return
    - 为无返回值方法使用void类型
  • type-never-return
    - 为永不返回的函数使用never类型

2. Modern Features (CRITICAL)

2. 现代特性(关键)

  • modern-constructor-promotion
    - Use constructor property promotion
  • modern-readonly-properties
    - Use readonly for immutable data
  • modern-readonly-classes
    - Use readonly classes
  • modern-enums
    - Use enums instead of constants
  • modern-attributes
    - Use attributes for metadata
  • modern-match-expression
    - Use match over switch
  • modern-named-arguments
    - Use named arguments for clarity
  • modern-nullsafe-operator
    - Use nullsafe operator (?->)
  • modern-arrow-functions
    - Use arrow functions for simple closures
  • modern-first-class-callables
    - Use first-class callable syntax
  • modern-constructor-promotion
    - 使用构造函数属性提升
  • modern-readonly-properties
    - 为不可变数据使用readonly属性
  • modern-readonly-classes
    - 使用readonly类
  • modern-enums
    - 使用枚举替代常量
  • modern-attributes
    - 使用属性存储元数据
  • modern-match-expression
    - 使用match替代switch
  • modern-named-arguments
    - 使用命名参数提升代码清晰度
  • modern-nullsafe-operator
    - 使用空安全运算符 (?->)
  • modern-arrow-functions
    - 为简单闭包使用箭头函数
  • modern-first-class-callables
    - 使用一等可调用语法

3. PSR Standards (HIGH)

3. PSR标准(高)

  • psr-4-autoloading
    - Follow PSR-4 autoloading
  • psr-12-coding-style
    - Follow PSR-12 coding style
  • psr-naming-conventions
    - Class and method naming
  • psr-file-structure
    - One class per file
  • psr-namespace-declaration
    - Proper namespace usage
  • psr-4-autoloading
    - 遵循PSR-4自动加载规范
  • psr-12-coding-style
    - 遵循PSR-12编码风格
  • psr-naming-conventions
    - 类与方法命名规范
  • psr-file-structure
    - 一个文件对应一个类
  • psr-namespace-declaration
    - 正确使用命名空间

4. SOLID Principles (HIGH)

4. SOLID原则(高)

  • solid-single-responsibility
    - One reason to change
  • solid-open-closed
    - Open for extension, closed for modification
  • solid-liskov-substitution
    - Subtypes must be substitutable
  • solid-interface-segregation
    - Small, focused interfaces
  • solid-dependency-inversion
    - Depend on abstractions
  • solid-single-responsibility
    - 单一职责原则(一个类只有一个修改理由)
  • solid-open-closed
    - 开闭原则(对扩展开放,对修改关闭)
  • solid-liskov-substitution
    - 里氏替换原则(子类必须可以替换父类)
  • solid-interface-segregation
    - 接口隔离原则(使用小而专注的接口)
  • solid-dependency-inversion
    - 依赖倒置原则(依赖于抽象而非具体实现)

5. Error Handling (HIGH)

5. 错误处理(高)

  • error-custom-exceptions
    - Create specific exceptions
  • error-exception-hierarchy
    - Proper exception inheritance
  • error-try-catch-specific
    - Catch specific exceptions
  • error-finally-cleanup
    - Use finally for cleanup
  • error-never-suppress
    - Don't suppress errors with @
  • error-custom-exceptions
    - 创建特定的自定义异常
  • error-exception-hierarchy
    - 正确的异常继承体系
  • error-try-catch-specific
    - 捕获特定类型的异常
  • error-finally-cleanup
    - 使用finally进行资源清理
  • error-never-suppress
    - 不要使用@抑制错误

6. Performance (MEDIUM)

6. 性能优化(中)

  • perf-avoid-globals
    - Avoid global variables
  • perf-lazy-loading
    - Load resources lazily
  • perf-array-functions
    - Use native array functions
  • perf-string-functions
    - Use native string functions
  • perf-generators
    - Use generators for large datasets
  • perf-avoid-globals
    - 避免使用全局变量
  • perf-lazy-loading
    - 延迟加载资源
  • perf-array-functions
    - 使用原生数组函数
  • perf-string-functions
    - 使用原生字符串函数
  • perf-generators
    - 为大型数据集使用生成器

7. Security (CRITICAL)

7. 安全防护(关键)

  • sec-input-validation
    - Validate all input
  • sec-output-escaping
    - Escape output properly
  • sec-password-hashing
    - Use password_hash/verify
  • sec-sql-prepared
    - Use prepared statements
  • sec-file-uploads
    - Validate file uploads
  • sec-input-validation
    - 验证所有输入
  • sec-output-escaping
    - 正确转义输出
  • sec-password-hashing
    - 使用password_hash/verify进行密码哈希
  • sec-sql-prepared
    - 使用预处理语句
  • sec-file-uploads
    - 验证文件上传

Essential Guidelines

核心指南

For detailed examples and explanations, see the rule files:
  • type-strict-mode.md - Strict types declaration
  • modern-constructor-promotion.md - Constructor property promotion
  • modern-enums.md - PHP 8.1+ enums with methods
  • solid-single-responsibility.md - Single responsibility principle
如需详细示例与解释,请查看规则文件:
  • type-strict-mode.md - 严格类型声明
  • modern-constructor-promotion.md - 构造函数属性提升
  • modern-enums.md - PHP 8.1+带方法的枚举
  • solid-single-responsibility.md - 单一职责原则

Key Patterns (Quick Reference)

核心模式(快速参考)

php
<?php
declare(strict_types=1);

// Constructor promotion + readonly
class User
{
    public function __construct(
        public readonly string $id,
        private string $email,
    ) {}
}

// Enums with methods
enum Status: string
{
    case Active = 'active';
    case Inactive = 'inactive';

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

// Match expression
$result = match($status) {
    'pending' => 'Waiting',
    'active' => 'Running',
    default => 'Unknown',
};

// Nullsafe operator
$country = $user?->getAddress()?->getCountry();

// Arrow functions
$names = array_map(fn(User $u) => $u->name, $users);
php
<?php
declare(strict_types=1);

// Constructor promotion + readonly
class User
{
    public function __construct(
        public readonly string $id,
        private string $email,
    ) {}
}

// Enums with methods
enum Status: string
{
    case Active = 'active';
    case Inactive = 'inactive';

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

// Match expression
$result = match($status) {
    'pending' => 'Waiting',
    'active' => 'Running',
    default => 'Unknown',
};

// Nullsafe operator
$country = $user?->getAddress()?->getCountry();

// Arrow functions
$names = array_map(fn(User $u) => $u->name, $users);

Output Format

输出格式

When auditing code, output findings in this format:
file:line - [category] Description of issue
Example:
src/Services/UserService.php:15 - [type] Missing return type declaration
src/Models/Order.php:42 - [modern] Use match expression instead of switch
src/Controllers/ApiController.php:28 - [solid] Class has multiple responsibilities
审计代码时,请按以下格式输出结果:
file:line - [category] 问题描述
示例:
src/Services/UserService.php:15 - [type] 缺少返回类型声明
src/Models/Order.php:42 - [modern] 使用match表达式替代switch
src/Controllers/ApiController.php:28 - [solid] 类承担了多个职责

How to Use

使用方法

Read individual rule files for detailed explanations:
rules/modern-constructor-promotion.md
rules/type-strict-mode.md
rules/solid-single-responsibility.md
查看单个规则文件获取详细解释:
rules/modern-constructor-promotion.md
rules/type-strict-mode.md
rules/solid-single-responsibility.md