PSR-12 is a coding style guideline defined by the PHP-FIG (PHP Framework Interoperability Group). It builds on PSR-1 (Basic Coding Standard) and PSR-2 (Coding Style Guide), extending them to include modern practices and requirements.
PSR-12 aims to establish a consistent and readable code style for PHP projects, facilitating collaboration between developers and maintaining a uniform codebase.
namespace
declaration.use
statements should follow the namespace
declaration.namespace App\Controller;
use App\Service\MyService;
use Psr\Log\LoggerInterface;
{
for a class or method must be placed on the next line.public
, protected
, private
) is mandatory for all methods and properties.class MyClass
{
private string $property;
public function myMethod(): void
{
// code
}
}
public function myFunction(
int $param1,
string $param2
): string {
return 'example';
}
{
must be on the same line as the control structure.if ($condition) {
// code
} elseif ($otherCondition) {
// code
} else {
// code
}
[]
) for arrays.$array = [
'first' => 'value1',
'second' => 'value2',
];
?
.public function getValue(?int $id): ?string
{
return $id !== null ? (string) $id : null;
}
<?php
tag and must not include a closing ?>
tag.PSR-12 extends PSR-2 by:
PSR-12 is the standard for modern and consistent PHP code. It improves code quality and simplifies collaboration, especially in team environments. Tools like PHP_CodeSniffer
or PHP-CS-Fixer
can help ensure adherence to PSR-12 effortlessly.
PHP Mess Detector (PHPMD) is a static analysis tool for PHP that helps detect potential problems in your code. It identifies a wide range of code issues, including:
PHPMD is configurable, allowing you to define custom rules or use predefined rule sets like "unused code" or "naming conventions." It works similarly to PHP_CodeSniffer, but while CodeSniffer focuses more on style and formatting issues, PHPMD is more focused on the logic and structure of the code.
In summary, PHPMD helps ensure code quality and maintainability by pointing out potential "messes" that might otherwise go unnoticed.
PHP_CodeSniffer, often referred to as "Codesniffer," is a tool used to detect violations of coding standards in PHP code. It ensures that code adheres to specified standards, which improves readability, consistency, and maintainability across projects.
In summary, PHP_CodeSniffer helps improve the overall quality and consistency of PHP projects, making them easier to maintain in the long term.