php-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePHP 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
按优先级划分的规则类别
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Type System | CRITICAL | |
| 2 | Modern Features | CRITICAL | |
| 3 | PSR Standards | HIGH | |
| 4 | SOLID Principles | HIGH | |
| 5 | Error Handling | HIGH | |
| 6 | Performance | MEDIUM | |
| 7 | Security | CRITICAL | |
| 优先级 | 类别 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | 类型系统 | 关键 | |
| 2 | 现代特性 | 关键 | |
| 3 | PSR标准 | 高 | |
| 4 | SOLID原则 | 高 | |
| 5 | 错误处理 | 高 | |
| 6 | 性能优化 | 中 | |
| 7 | 安全防护 | 关键 | |
Quick Reference
快速参考
1. Type System (CRITICAL)
1. 类型系统(关键)
- - Declare strict types
type-strict-mode - - Always declare return types
type-return-types - - Type all parameters
type-parameter-types - - Type class properties
type-property-types - - Use union types effectively
type-union-types - - Use intersection types
type-intersection-types - - Handle nullable types properly
type-nullable - - Avoid mixed type when possible
type-mixed-avoid - - Use void for no-return methods
type-void-return - - Use never for non-returning functions
type-never-return
- - 声明严格类型
type-strict-mode - - 始终声明返回类型
type-return-types - - 为所有参数指定类型
type-parameter-types - - 为类属性指定类型
type-property-types - - 有效使用联合类型
type-union-types - - 使用交叉类型
type-intersection-types - - 正确处理可空类型
type-nullable - - 尽可能避免使用mixed类型
type-mixed-avoid - - 为无返回值方法使用void类型
type-void-return - - 为永不返回的函数使用never类型
type-never-return
2. Modern Features (CRITICAL)
2. 现代特性(关键)
- - Use constructor property promotion
modern-constructor-promotion - - Use readonly for immutable data
modern-readonly-properties - - Use readonly classes
modern-readonly-classes - - Use enums instead of constants
modern-enums - - Use attributes for metadata
modern-attributes - - Use match over switch
modern-match-expression - - Use named arguments for clarity
modern-named-arguments - - Use nullsafe operator (?->)
modern-nullsafe-operator - - Use arrow functions for simple closures
modern-arrow-functions - - Use first-class callable syntax
modern-first-class-callables
- - 使用构造函数属性提升
modern-constructor-promotion - - 为不可变数据使用readonly属性
modern-readonly-properties - - 使用readonly类
modern-readonly-classes - - 使用枚举替代常量
modern-enums - - 使用属性存储元数据
modern-attributes - - 使用match替代switch
modern-match-expression - - 使用命名参数提升代码清晰度
modern-named-arguments - - 使用空安全运算符 (?->)
modern-nullsafe-operator - - 为简单闭包使用箭头函数
modern-arrow-functions - - 使用一等可调用语法
modern-first-class-callables
3. PSR Standards (HIGH)
3. PSR标准(高)
- - Follow PSR-4 autoloading
psr-4-autoloading - - Follow PSR-12 coding style
psr-12-coding-style - - Class and method naming
psr-naming-conventions - - One class per file
psr-file-structure - - Proper namespace usage
psr-namespace-declaration
- - 遵循PSR-4自动加载规范
psr-4-autoloading - - 遵循PSR-12编码风格
psr-12-coding-style - - 类与方法命名规范
psr-naming-conventions - - 一个文件对应一个类
psr-file-structure - - 正确使用命名空间
psr-namespace-declaration
4. SOLID Principles (HIGH)
4. SOLID原则(高)
- - One reason to change
solid-single-responsibility - - Open for extension, closed for modification
solid-open-closed - - Subtypes must be substitutable
solid-liskov-substitution - - Small, focused interfaces
solid-interface-segregation - - Depend on abstractions
solid-dependency-inversion
- - 单一职责原则(一个类只有一个修改理由)
solid-single-responsibility - - 开闭原则(对扩展开放,对修改关闭)
solid-open-closed - - 里氏替换原则(子类必须可以替换父类)
solid-liskov-substitution - - 接口隔离原则(使用小而专注的接口)
solid-interface-segregation - - 依赖倒置原则(依赖于抽象而非具体实现)
solid-dependency-inversion
5. Error Handling (HIGH)
5. 错误处理(高)
- - Create specific exceptions
error-custom-exceptions - - Proper exception inheritance
error-exception-hierarchy - - Catch specific exceptions
error-try-catch-specific - - Use finally for cleanup
error-finally-cleanup - - Don't suppress errors with @
error-never-suppress
- - 创建特定的自定义异常
error-custom-exceptions - - 正确的异常继承体系
error-exception-hierarchy - - 捕获特定类型的异常
error-try-catch-specific - - 使用finally进行资源清理
error-finally-cleanup - - 不要使用@抑制错误
error-never-suppress
6. Performance (MEDIUM)
6. 性能优化(中)
- - Avoid global variables
perf-avoid-globals - - Load resources lazily
perf-lazy-loading - - Use native array functions
perf-array-functions - - Use native string functions
perf-string-functions - - Use generators for large datasets
perf-generators
- - 避免使用全局变量
perf-avoid-globals - - 延迟加载资源
perf-lazy-loading - - 使用原生数组函数
perf-array-functions - - 使用原生字符串函数
perf-string-functions - - 为大型数据集使用生成器
perf-generators
7. Security (CRITICAL)
7. 安全防护(关键)
- - Validate all input
sec-input-validation - - Escape output properly
sec-output-escaping - - Use password_hash/verify
sec-password-hashing - - Use prepared statements
sec-sql-prepared - - Validate file uploads
sec-file-uploads
- - 验证所有输入
sec-input-validation - - 正确转义输出
sec-output-escaping - - 使用password_hash/verify进行密码哈希
sec-password-hashing - - 使用预处理语句
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 issueExample:
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