php-best-practices
asyrafhussin/agent-skills
PHP 8.x modern patterns, PSR standards, and SOLID principles for code review and quality audits.
What is php-best-practices?
Comprehensive guide for reviewing and auditing PHP code against 51 rules covering type safety, modern PHP 8.x features, PSR standards, SOLID principles, error handling, performance, and security. Use when reviewing PHP code, checking type safety, auditing code quality, or ensuring PHP best practices.
- Detects PHP version from composer.json and runtime to suggest only applicable features
- Enforces strict typing, return types, and parameter types across all code
- Recommends modern PHP 8.x patterns: constructor promotion, match expressions, enums, readonly properties, property hooks, and pipe operator
- Validates PSR-4 autoloading, PSR-12 coding style, and naming conventions
- Applies SOLID principles: single responsibility, open/closed, Liskov substitution, interface segregation, and dependency inversion
- Audits error handling, security (input validation, output escaping, SQL prepared statements), and performance optimizations
How to install php-best-practices
npx skills add https://github.com/asyrafhussin/agent-skills --skill php-best-practices- PHP 8.0 or higher installed
- Access to composer.json to detect project PHP version requirement
How to use php-best-practices
- 1.Check the project's PHP version in composer.json or via `php -v` to determine which features are available
- 2.Review the rule categories (Type System, Modern Features, PSR Standards, SOLID, Error Handling, Performance, Security)
- 3.Apply relevant rules based on the detected PHP version—only suggest features available in that version
- 4.Use the output format `file:line - [category] Description` when reporting audit findings
- 5.Reference specific rule files (type-strict-mode.md, modern-constructor-promotion.md, etc.) for detailed examples and explanations
Use cases
- Review PHP code for type safety and modern pattern adoption before merging pull requests
- Audit existing PHP codebase for security vulnerabilities and best practice violations
- Guide refactoring of legacy PHP code to PHP 8.x patterns and SOLID principles
- Validate new code against PSR standards and organizational coding guidelines
- Check for proper error handling, input validation, and secure password/SQL practices
- PHP developers writing or reviewing code
- Code auditors ensuring quality and security standards
- Teams migrating legacy PHP to PHP 8.x
- Developers learning modern PHP patterns and SOLID principles
php-best-practices FAQ
Check your project's `composer.json` for the required PHP version (e.g., `"php": "^8.3"`). Only suggest features available in that version. The skill includes a feature availability table showing which features are available in 8.0+, 8.1+, 8.2+, 8.3+, 8.4+, and 8.5+.
Union types (8.0+) allow a parameter to be one of several types: `string|int`. Intersection types (8.1+) require a parameter to satisfy multiple type constraints: `Countable&ArrayAccess`. Use union types for flexibility and intersection types for strict multi-interface compliance.
Prefer match expressions (8.0+) over switch statements. Match is more concise, returns a value, uses strict comparison (===), and prevents accidental fallthrough bugs.
Readonly properties (8.1+) can only be assigned once, typically in the constructor. They prevent accidental mutation and make immutable data structures explicit and safe.
Create specific exception classes for different errors, catch specific exceptions (not generic \Exception), use finally for guaranteed cleanup, never suppress errors with @, and validate/sanitize all external input before processing.
Full instructions (SKILL.md)
Source of truth, from asyrafhussin/agent-skills.
name: php-best-practices 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". license: MIT metadata: author: php-community version: "2.1.0" phpVersion: "8.0 - 8.5"
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
Related skills
More from asyrafhussin/agent-skills and the wider catalog.

react-vite-best-practices
23 React + Vite performance optimization rules for build, code splitting, and bundle efficiency.

clean-code-principles
SOLID principles, design patterns, DRY, KISS, and clean code fundamentals. Use when reviewing architecture, checking code quality, refactoring, or discussing design decisions. Triggers on "review architecture", "check code quality", "SOLID principles", "design patterns", or "clean code".

laravel-best-practices
Laravel 13 conventions and best practices. Use when creating controllers, models, migrations, validation, services, or structuring Laravel applications. Triggers on tasks involving Laravel architecture, Eloquent, database, API development, or PHP patterns.

laravel-inertia-react
Laravel + Inertia.js + React integration patterns. Use when building Inertia page components, handling forms with useForm, managing shared data, or implementing persistent layouts. Triggers on tasks involving Inertia.js, page props, form handling, or Laravel React integration.
atxp
Agent wallet, identity, and paid tools—register, fund via Stripe/USDC, access 100+ LLM models and paid APIs.
atxp-memory
Agent memory management — cloud backup, restore, and local vector search of .md memory files