php-best-practices▌
asyrafhussin/agent-skills · updated Apr 8, 2026
MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.
51 rules for writing clean, type-safe, modern PHP 8.x code aligned with PSR standards and SOLID principles.
- ›Covers 7 rule categories: type system, modern PHP features (8.0–8.5), PSR standards, SOLID principles, error handling, performance, and security
- ›Version-aware guidance that detects PHP version from composer.json and runtime, recommending only features available in the target version
- ›Organized by priority: type safety and security are critical; modern features and SOLID principl
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 responsiHow to use php-best-practices on Cursor
AI-first code editor with Composer
Prerequisites
Before installing skills in Cursor, ensure your development environment meets these requirements:
- ›Cursor installed and configured on your development machine
- ›Node.js version 16.0+ with npm package manager (verify with
node --version) - ›Active project directory or workspace where you want to add php-best-practices
Execute installation command
Execute the skills CLI command in your project's root directory to begin installation:
The skills CLI fetches php-best-practices from GitHub repository asyrafhussin/agent-skills and configures it for Cursor.
Select Cursor when prompted
The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:
Verify installation
Confirm successful installation by checking the skill directory location:
Reload or restart Cursor to activate php-best-practices. Access the skill through slash commands (e.g., /php-best-practices) or your agent's skill management interface.
Security & Verification Notice
We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.
Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.
List & Monetize Your Skill
Submit your Claude Code skill and start earning
Use Cases▌
User Story & Requirements Generation
Create detailed user stories, acceptance criteria, and feature specs
Example
Generate user stories for 'password reset feature' with acceptance criteria, edge cases, and test scenarios
Reduce spec writing time by 50%, ensure comprehensive coverage
Competitive Analysis
Research competitors, compare features, identify gaps
Example
Analyze 5 competitor products, create feature comparison matrix, suggest differentiation opportunities
Complete competitive research in 2 hours instead of 2 days
Roadmap Prioritization
Evaluate features using frameworks (RICE, ICE, Kano) and create prioritized backlogs
Example
Score 20 feature ideas using RICE framework, generate prioritized roadmap with rationale
Make data-driven prioritization decisions faster
Stakeholder Communication
Draft PRDs, status updates, and stakeholder presentations
Example
Create executive summary of Q3 roadmap, monthly progress report, feature launch announcement
Save 3-5 hours/week on communication overhead
Implementation Guide▌
Prerequisites
- ›Claude Desktop or compatible AI client
- ›Access to product documentation and roadmap tools (Jira, Notion, etc.)
- ›Understanding of product management frameworks (RICE, Jobs-to-be-Done, etc.)
- ›Stakeholder contact information and communication channels
Time Estimate
30-60 minutes to see productivity improvements
Installation Steps
- 1.Install product management skill
- 2.Start with user story generation for known feature
- 3.Progress to competitive analysis: research 2-3 competitors
- 4.Use for roadmap prioritization: apply RICE/ICE scoring
- 5.Draft stakeholder communications and refine based on feedback
- 6.Build template library for recurring PM tasks
- 7.Share effective prompts with product team
Common Pitfalls
- ⚠Not validating competitive research—verify facts before sharing
- ⚠Accepting user stories without involving engineering team
- ⚠Over-relying on frameworks without qualitative judgment
- ⚠Not customizing outputs to company culture and communication style
- ⚠Skipping stakeholder validation of generated requirements
Best Practices▌
✓ Do
- +Validate research and competitive analysis with real data
- +Collaborate with engineering when generating technical requirements
- +Customize frameworks and templates to your company context
- +Use skill for first drafts, refine with stakeholder input
- +Document successful prompt patterns for PM tasks
- +Combine AI efficiency with human judgment and intuition
✗ Don't
- −Don't publish competitive analysis without fact-checking
- −Don't finalize user stories without engineering review
- −Don't make prioritization decisions solely on AI scoring
- −Don't skip customer validation of generated requirements
- −Don't ignore company-specific context and culture
💡 Pro Tips
- ★Provide context: company goals, constraints, customer feedback
- ★Ask for alternatives: 'Show 3 ways to prioritize this roadmap'
- ★Request stakeholder-specific formatting: 'Executive summary vs. engineering spec'
- ★Use skill for 70% generation + 30% customization to company needs
When to Use This▌
✓ Use When
Use for user story writing, competitive research, roadmap prioritization, stakeholder communication, and PRD drafting. Best for reducing repetitive documentation and research work.
✗ Avoid When
Avoid for strategic product vision (requires deep customer empathy), pricing decisions (needs market and financial expertise), or when face-to-face customer discovery is more valuable than speed.
Learning Path▌
- 1Basic: user stories, feature specs, status updates
- 2Intermediate: competitive analysis, prioritization frameworks, PRDs
- 3Advanced: product strategy, go-to-market planning, OKR setting
- 4Expert: product vision, market positioning, business model innovation
Discussion
Product Hunt–style comments (not star reviews)- No comments yet — start the thread.
Ratings
4.8★★★★★41 reviews- ★★★★★Ganesh Mohane· Dec 28, 2024
Useful defaults in php-best-practices — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.
- ★★★★★Zara Patel· Dec 16, 2024
php-best-practices is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.
- ★★★★★Naina Gupta· Dec 16, 2024
Registry listing for php-best-practices matched our evaluation — installs cleanly and behaves as described in the markdown.
- ★★★★★Yusuf Sharma· Dec 12, 2024
I recommend php-best-practices for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.
- ★★★★★Shikha Mishra· Dec 4, 2024
Keeps context tight: php-best-practices is the kind of skill you can hand to a new teammate without a long onboarding doc.
- ★★★★★Aditi Khanna· Dec 4, 2024
Useful defaults in php-best-practices — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.
- ★★★★★Yash Thakker· Nov 23, 2024
Registry listing for php-best-practices matched our evaluation — installs cleanly and behaves as described in the markdown.
- ★★★★★Tariq Agarwal· Nov 7, 2024
php-best-practices reduced setup friction for our internal harness; good balance of opinion and flexibility.
- ★★★★★Aisha Agarwal· Nov 7, 2024
Keeps context tight: php-best-practices is the kind of skill you can hand to a new teammate without a long onboarding doc.
- ★★★★★Naina Iyer· Oct 26, 2024
Registry listing for php-best-practices matched our evaluation — installs cleanly and behaves as described in the markdown.
showing 1-10 of 41