PSR-12 extends PSR-1 and PSR-2 (now deprecated) to provide a comprehensive coding style guide for modern PHP. This standard ensures consistency across PHP code by defining specific formatting rules.
Key Style Rules
1. General Code Layout
- Files MUST use Unix LF line endings.
- Files MUST end with a single blank line.
- The closing
?>
tag MUST be omitted from files containing only PHP. - Lines SHOULD be 80 characters or less.
- There MUST be one blank line after namespace declarations.
- Opening braces MUST be on the same line as the statement.
2. Class Structure
Here’s an example of a properly structured class:
<?php
declare(strict_types=1);
namespace Vendor\Package;
use Vendor\Package\SomeClass;
use Vendor\Package\AnotherClass as AClass;
class ClassName extends ParentClass implements \ArrayAccess, \Countable
{
private const VERSION = '1.0';
public function methodName(int $arg1, ?string $arg2): string
{
// method body
}
}
3. Control Structures
Examples of control structures formatted according to PSR-12:
<?php
if ($expr1) {
// if body
} elseif ($expr2) {
// elseif body
} else {
// else body
}
switch ($expr) {
case 0:
echo 'First case';
break;
default:
echo 'Default case';
break;
}
try {
// try body
} catch (FirstThrowableType $e) {
// catch body
} finally {
// finally body
}
Modern PHP Features
1. Type Declarations
Example of using type declarations in method signatures:
<?php
public function processUser(
User $user,
?array $options = null
): ?Response {
// Implementation
}
2. Attribute Syntax
Example of using attribute syntax in PHP 8:
<?php
#[Route("/api/posts/{id}", methods: ["GET"])]
public function show(#[EntityId] int $id): Response
{
// Implementation
}
Tools for PSR-12 Compliance
- PHP_CodeSniffer Configuration
- PHP-CS-Fixer Setup
- IDE Integration
- PhpStorm
- VS Code with PHP Intelephense
Common Issues and Solutions
- Mixed Line Endings
# Check for mixed line endings
$ find . -name "*.php" -exec file {} \;
# Fix with dos2unix
$ find . -name "*.php" -exec dos2unix {} \;
- Incorrect Indentation
// Bad
class Foo {
function bar() {
return true;
}
}
// Good
class Foo
{
public function bar(): bool
{
return true;
}
}
Next Steps
In our next post, we’ll explore PSR-13, which defines standards for HTTP message interfaces in PHP. Check out our example repository for the implementation of these standards.
Resources
Example: Declare Statements
<?php
declare(strict_types=1);
namespace Vendor\Package;
use Vendor\Package\{ClassA as A, ClassB, ClassC as C};
use Vendor\Package\SomeNamespace\ClassD as D;
Example: Class Structure
<?php
namespace Vendor\Package;
class ClassName extends ParentClass implements \ArrayAccess, \Countable
{
private $property;
public function __construct()
{
// constructor body
}
}
Baamaapii 👋
Top comments (0)