Ever wondered why some PHP codebases are a joy to work with while others feel like a maze? A lot of it comes down to following consistent coding standards. Let’s explore PSR-1, the foundation of modern PHP development that helps teams write cleaner, more maintainable code!
Overview of PSR-1 Rules
1. Files and Namespaces
- Files MUST use only
- Files MUST use only UTF-8 without BOM for PHP code
- Files SHOULD either declare symbols (classes, functions, constants) OR cause side-effects (generate output, modify settings, etc.) but SHOULD NOT do both
2. Namespace and Class Names
- Classes MUST be declared in StudlyCaps
- Class constants MUST be declared in all upper case with underscore separators
3. Class Methods
- Method names MUST be declared in camelCase
Practical Implementation
Let’s look at a correct PSR-1 implementation from our example repository:
$id, 'name' => 'John Doe'];
}
}
This example demonstrates:
- Proper namespace declaration using StudlyCaps
- Class name in StudlyCaps
- Constants in uppercase with underscores
- Method name in camelCase
Common Violations and Fixes
Mixed Responsibilities
Incorrect Naming
Integration with Modern PHP Tools
Our example repository includes setup for:
- PHP_CodeSniffer for PSR-1 validation (composer check-style)
- Automated style fixing (composer fix-style)
- PHPUnit for testing implementations
- Composer autoloading following PSR-4
Next Steps
In our next post, we’ll explore PSR-12, which extends these basic coding standards with more comprehensive style guidelines. This post is part of our PSR Standards in PHP series.
Resources
- Official PSR-1 Specification
- PHP_CodeSniffer PSR-1 Ruleset
-
Series Example Repository (v0.1.0 - PSR-1 Implementation)
The above is the detailed content of PSR-Basic Coding Standard in PHP. For more information, please follow other related articles on the PHP Chinese website!