php-best-practices
PHP 8.x modern patterns, PSR standards, and SOLID principles. Use when reviewing PHP code, checking type safety, auditing code quality, or ensuring PHP best practices. Triggers on "review PHP", "check PHP code", "audit PHP", or "PHP best practices".
- License 许可
- MIT
- 最近更新
- 2026-09-09
- Stars
- ★ 1
- Forks
- 0
01 前言 Front Matter
- name
- php-best-practices
- license
- MIT
- metadata
- { "author": "php-community", "version": "2.1.0", "phpVersion": "8.0 - 8.5" }
- description
- PHP 8.x modern patterns, PSR standards, and SOLID principles. Use when reviewing PHP code, checking type safety, auditing code quality, or ensuring PHP best practices. Triggers on "review PHP", "check PHP code", "audit PHP", or "PHP best practices".
02 资源文件 55
- 参考文档AGENTS.md20.8 KB
- 参考文档README.md2.2 KB
- 参考文档rules/_sections.md2.0 KB
- 参考文档rules/_template.md1018 B
- 参考文档rules/error-custom-exceptions.md3.5 KB
- 参考文档rules/error-exception-hierarchy.md3.4 KB
- 参考文档rules/error-finally-cleanup.md2.6 KB
- 参考文档rules/error-never-suppress.md2.4 KB
- 参考文档rules/error-try-catch-specific.md2.5 KB
- 参考文档rules/modern-arrow-functions.md3.3 KB
- 参考文档rules/modern-asymmetric-visibility.md2.7 KB
- 参考文档rules/modern-attributes.md3.9 KB
- 参考文档rules/modern-constructor-promotion.md4.1 KB
- 参考文档rules/modern-enums-methods.md4.7 KB
- 参考文档rules/modern-enums.md6.8 KB
- 参考文档rules/modern-first-class-callables.md4.5 KB
- 参考文档rules/modern-match-expression.md3.7 KB
- 参考文档rules/modern-named-arguments.md3.1 KB
- 参考文档rules/modern-nullsafe-operator.md3.6 KB
- 参考文档rules/modern-override-attribute.md2.6 KB
- 参考文档rules/modern-pipe-operator.md2.6 KB
- 参考文档rules/modern-property-hooks.md3.1 KB
- 参考文档rules/modern-readonly-classes.md3.3 KB
- 参考文档rules/modern-readonly-properties.md3.1 KB
- 参考文档rules/modern-typed-constants.md2.3 KB
- 参考文档rules/perf-array-functions.md2.2 KB
- 参考文档rules/perf-avoid-globals.md2.1 KB
- 参考文档rules/perf-generators.md2.8 KB
- 参考文档rules/perf-lazy-loading.md2.6 KB
- 参考文档rules/perf-string-functions.md2.0 KB
- 参考文档rules/psr-12-coding-style.md4.7 KB
- 参考文档rules/psr-4-autoloading.md3.0 KB
- 参考文档rules/psr-file-structure.md5.0 KB
- 参考文档rules/psr-namespace-usage.md4.9 KB
- 参考文档rules/psr-naming-classes.md3.6 KB
- 参考文档rules/psr-naming-methods.md5.7 KB
- 参考文档rules/sec-file-uploads.md3.6 KB
- 参考文档rules/sec-input-validation.md2.6 KB
- 参考文档rules/sec-output-escaping.md2.1 KB
- 参考文档rules/sec-password-hashing.md2.6 KB
- 参考文档rules/sec-sql-prepared.md2.6 KB
- 参考文档rules/solid-dip.md7.0 KB
- 参考文档rules/solid-isp.md6.7 KB
- 参考文档rules/solid-lsp.md6.5 KB
- 参考文档rules/solid-ocp.md6.8 KB
- 参考文档rules/solid-srp.md6.7 KB
- 参考文档rules/type-intersection-types.md2.6 KB
- 参考文档rules/type-mixed-avoid.md3.0 KB
- 参考文档rules/type-nullable-types.md2.5 KB
- 参考文档rules/type-parameter-types.md1.8 KB
- 参考文档rules/type-property-types.md1.9 KB
- 参考文档rules/type-return-types.md1.8 KB
- 参考文档rules/type-strict-mode.md4.6 KB
- 参考文档rules/type-union-types.md2.0 KB
- 参考文档rules/type-void-never.md2.9 KB
03 SKILL.md 正文
PHP Best Practices
Modern PHP 8.x patterns, PSR standards, type system best practices, and SOLID principles. Contains 51 rules for writing clean, maintainable PHP code.
Step 1: Detect PHP Version
Always check the project's PHP version before giving any advice. Features vary significantly across 8.0 - 8.5. Never suggest syntax that doesn't exist in the project's version.
Check composer.json for the required PHP version:
{ "require": { "php": "^8.1" } } // -> 8.1 rules and below
{ "require": { "php": "^8.3" } } // -> 8.3 rules and below
{ "require": { "php": ">=8.4" } } // -> 8.4 rules and below
Also check the runtime version:
php -v # e.g. PHP 8.3.12
Feature Availability by Version
| Feature | Version | Rule Prefix |
|---|---|---|
| Union types, match, nullsafe, named args, constructor promotion, attributes | 8.0+ | type-, modern- |
| Enums, readonly properties, intersection types, first-class callables, never, fibers | 8.1+ | modern- |
| Readonly classes, DNF types, true/false/null standalone types | 8.2+ | modern- |
Typed class constants, #[\Override], json_validate() |
8.3+ | modern- |
Property hooks, asymmetric visibility, #[\Deprecated], new without parens |
8.4+ | modern- |
| Pipe operator ` | >` | 8.5+ |
Only suggest features available in the detected version. If the user asks about upgrading or newer features, mention what becomes available at each version.
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
Rule Categories by Priority
| Priority | Category | Impact | Prefix | Rules |
|---|---|---|---|---|
| 1 | Type System | CRITICAL | type- |
9 |
| 2 | Modern PHP Features | CRITICAL | modern- |
16 |
| 3 | PSR Standards | HIGH | psr- |
6 |
| 4 | SOLID Principles | HIGH | solid- |
5 |
| 5 | Error Handling | HIGH | error- |
5 |
| 6 | Performance | MEDIUM | perf- |
5 |
| 7 | Security | CRITICAL | sec- |
5 |
Quick Reference
1. Type System (CRITICAL) — 9 rules
type-strict-mode- Declare strict types in every filetype-return-types- Always declare return typestype-parameter-types- Type all parameterstype-property-types- Type class propertiestype-union-types- Use union types effectivelytype-intersection-types- Use intersection typestype-nullable-types- Handle nullable types properlytype-void-never- Use void/never for appropriate return typestype-mixed-avoid- Avoid mixed type when possible
2. Modern PHP Features (CRITICAL) — 16 rules
8.0+:
modern-constructor-promotion- Constructor property promotionmodern-match-expression- Match over switchmodern-named-arguments- Named arguments for claritymodern-nullsafe-operator- Nullsafe operator (?->)modern-attributes- Attributes for metadata
8.1+:
modern-enums- Enums instead of constantsmodern-enums-methods- Enums with methods and interfacesmodern-readonly-properties- Readonly for immutable datamodern-first-class-callables- First-class callable syntaxmodern-arrow-functions- Arrow functions (7.4+, pairs well with 8.1 features)
8.2+:
modern-readonly-classes- Readonly classes
8.3+:
modern-typed-constants- Typed class constants (const string NAME = 'foo')modern-override-attribute-#[\Override]to catch parent method typos
8.4+:
modern-property-hooks- Property hooks replacing getters/settersmodern-asymmetric-visibility-public private(set)for controlled access
8.5+:
modern-pipe-operator- Pipe operator (|>) for functional chaining
3. PSR Standards (HIGH) — 6 rules
psr-4-autoloading- Follow PSR-4 autoloadingpsr-12-coding-style- Follow PSR-12 coding stylepsr-naming-classes- Class naming conventionspsr-naming-methods- Method naming conventionspsr-file-structure- One class per filepsr-namespace-usage- Proper namespace usage
4. SOLID Principles (HIGH) — 5 rules
solid-srp- Single Responsibility: one reason to changesolid-ocp- Open/Closed: extend, don't modifysolid-lsp- Liskov Substitution: subtypes must be substitutablesolid-isp- Interface Segregation: small, focused interfacessolid-dip- Dependency Inversion: depend on abstractions
5. Error Handling (HIGH) — 5 rules
error-custom-exceptions- Create specific exceptions for different errorserror-exception-hierarchy- Organize exceptions into meaningful hierarchyerror-try-catch-specific- Catch specific exceptions, not generic \Exceptionerror-finally-cleanup- Use finally for guaranteed resource cleanuperror-never-suppress- Never use @ error suppression operator
6. Performance (MEDIUM) — 5 rules
perf-avoid-globals- Avoid global variables, use dependency injectionperf-lazy-loading- Defer expensive operations until neededperf-array-functions- Use native array functions over manual loopsperf-string-functions- Use native string functions over regexperf-generators- Use generators for large datasets
7. Security (CRITICAL) — 5 rules
sec-input-validation- Validate and sanitize all external inputsec-output-escaping- Escape output based on context (HTML, JS, URL)sec-password-hashing- Use password_hash/verify, never MD5/SHA1sec-sql-prepared- Use prepared statements for all SQL queriessec-file-uploads- Validate file type, size, name; store outside web root
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-srp.md - Single responsibility principle
Key Patterns (Quick Reference)
<?php
declare(strict_types=1);
// 8.0+ Constructor promotion + readonly (8.1+)
class User
{
public function __construct(
public readonly string $id,
private string $email,
) {}
}
// 8.1+ 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',
};
}
}
// 8.0+ Match expression
$result = match($status) {
'pending' => 'Waiting',
'active' => 'Running',
default => 'Unknown',
};
// 8.0+ Nullsafe operator
$country = $user?->getAddress()?->getCountry();
// 8.3+ Typed class constants + #[\Override]
class PaymentService extends BaseService
{
public const string GATEWAY = 'stripe';
#[\Override]
public function process(): void { /* ... */ }
}
// 8.4+ Property hooks + asymmetric visibility
class Product
{
public string $name { set => trim($value); }
public private(set) float $price;
}
// 8.5+ Pipe operator
$result = $input
|> trim(...)
|> strtolower(...)
|> htmlspecialchars(...);
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
How to Use
Read individual rule files for detailed explanations:
rules/modern-constructor-promotion.md
rules/type-strict-mode.md
rules/solid-srp.md
04 同仓库更多 Skills
zustand-state-management
Production-tested setup for Zustand state management in React applications with TypeScript. This skill provides comprehensive patterns for building scalable, type-safe global state. Use when: setting up global state in React, migrating from Redux or Context API, implementing state persistence with localStorage, configuring TypeScript with Zustand, using slices pattern for modular stores, adding devtools middleware for debugging, handling Next.js SSR hydration, or encountering hydration errors, TypeScript inference issues, or persist middleware problems. Prevents 5 documented issues: Next.js hydration mismatches, TypeScript double parentheses syntax errors, persist middleware export errors, infinite render loops, and slices pattern type inference failures. Keywords: zustand, state management, React state, TypeScript state, persist middleware, devtools, slices pattern, global state, React hooks, create store, useBoundStore, StateCreator, hydration error, text content mismatch, infinite render, localStorage, sessionStorage, immer middleware, shallow equality, selector pattern, zustand v5
zetic-mlange
Help users integrate the ZETIC Melange (MLange) on-device AI SDK into Android (Kotlin/Java) and iOS (Swift) mobile apps. Use this skill whenever the user mentions Zetic, MLange, Melange, ZeticMLangeModel, ZeticMLangeLLMModel, ZeticMLangeHFModel, on-device NPU inference for mobile, or deploying ML models to Android/iOS with NPU acceleration. Also trigger when users ask about running LLMs on-device with GGUF quantization, mobile NPU model deployment, or converting PyTorch/ONNX models for mobile inference. Covers general model inference, LLM inference (streaming token generation), and HuggingFace model loading.
youtube-downloader
Download videos, audio, playlists, and channels from YouTube and 1000+ websites using yt-dlp. Supports quality selection, format conversion, subtitle download, playlist filtering, metadata extraction, thumbnail download, and batch operations. Use when downloading YouTube videos in any quality (4K, 8K, HDR), extracting audio as MP3/M4A/FLAC, downloading entire playlists/channels, getting subtitles in multiple languages, converting to specific formats, downloading live streams, archiving content, or batch processing multiple URLs. Optimized for reliability with automatic retries, rate limiting, and error handling.
wordpress-plugin-core
This skill provides comprehensive knowledge for WordPress plugin development, covering core patterns, security best practices, database interactions, hooks/filters, Settings API, custom post types, REST API, and AJAX. This skill should be used when creating WordPress plugins, troubleshooting security issues, implementing custom post types/taxonomies, building admin interfaces, or working with the WordPress database. Use when: Creating new WordPress plugins, implementing nonces/sanitization/escaping, working with $wpdb and prepared statements, building Settings API pages, registering custom post types or taxonomies, implementing REST API endpoints, handling AJAX requests, debugging plugin activation/deactivation issues, preventing SQL injection/XSS/CSRF vulnerabilities. Keywords: wordpress plugin development, wordpress security, wordpress hooks, wordpress filters, wordpress database, wpdb prepare, sanitize_text_field, esc_html, wp_nonce, custom post type, register_post_type, settings api, rest api, admin-ajax, wordpress sql injection, wordpress xss, wordpress csrf, plugin header, activation hook, deactivation hook, wordpress coding standards, wordpress plugin architecture
webapp-testing
Test local web applications with Playwright. Use when asked to verify frontend functionality, debug UI behavior, capture browser screenshots, or inspect browser logs.
web-performance-audit
Audit web performance using Chrome DevTools MCP. Use when asked to audit, profile, debug, or optimize page load performance, Lighthouse scores, or site speed.