PHP has PSR (PHP Standards Recommendations) which has an extensive list of standards but most developers follow some common standards which increase code readability and maintainability. In this article, I am going to share some of these most-followed standards by PHP Developers.
1. One class per file:
This standard suggests that if a PHP file has a class declaration then it should not have any other statements in the same file.
2. Function helpers should have only functions:
You must have encountered a composer auto-loaded helper file that has some common functions used through-out the application. It is recommended that such a helper file should have only function declarations and nothing else. It is also recommended that these function names should be in `snake_case` and not in `camelCase`.
3. Array properties should be on separate lines.
When one starts learning programming and control structure,
if__else is one of the first control structure that we learn but it is recommended to completely avoid the
else block in your code since you never need an else block, instead of using else block you can consider simplifying the code block.
5. Custom Exception Classes:
Most developers recommend using custom Exception classes extending from
\Exception class of PHP with a custom error message.
6. Make use of User-Defined constants:
It is recommended to use User-defined constants instead of using hard-coded values. It increases the readability of the code.
7. User Logical `!` operator instead of empty of NULL check:
Most developers prefer using the NOT (!) operator for NULL checks or empty checks.
8. Code case recommendations and standards:
- Class Names and Interfaces in CamelCase starting with a Capital Letter with Abstract classes should have word Abstract in the name and Interfaces should have word Interface in the Name.
- Function Names in camelCase starting with a Small Letter except for Functions in helpers file, snake_case for those.
- User-defined constants should be in CAPITAL_SNAKE_CASE.
- String Literals should be in ‘Single Quotes’ if they do not have variables.
When it comes to code formatting standards, there are various editor extensions available which does it for you, for PHP, I use PHPFmt with Visual Studio code which formats and aligns the code for better readability.
You can also install PHP Mess-detector with Visual Studio code which will give you warnings for Code mess.
Note: Almost all the points mentioned above are just recommendations and not mandatory.