In this post we are going to cover Magento coding standards for custom coding or any 3rd party extensions which have been used in the project. The Magento core development team itself uses PHP_CodeSniffer to follow a set of defined Magento rules and recommended to use the same tool to meet the standards.
PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that helps to detect violations in PHP, JavaScript and CSS files of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations.
Magento follows PSR-1 and PSR-2 coding standards so recommends you to use PHP_CodeSniffer which is an essential development tool that ensures your code remains clean and consistent.
The set of Magento rules is located in ruleset.xml file of Magento Coding Standard.
Magento Coding Standard provides a set of rules that covers the following:
- Raw MySql queries
- PSR-1 and PSR-2 compliance
- The use of insecure functions
- Unescaped output
- Use of deprecated PHP functions
- PHP code syntax
- Naming convention
- Use of PHP superglobals
- Empty code blocks
- Improper exception handling
Installation code sniffer within Magento 2:
To use coding standard tool in your Magento 2 project root directory, it can be installed easily by following below steps:
Installation Method -1
1 2 3 |
git clone git@github.com:magento/magento-coding-standard.git cd magento-coding-standard composer install |
Installation Method – 2
1 |
composer create-project magento/magento-coding-standard --stability=dev magento-coding-standard |
Verify installation
To validate installation, you can follow below mention steps:
1 2 3 4 5 |
cd magento-coding-standard/ vendor/bin/phpcs -i [this command will return installed coding standards i.e. magento2, PSR1] |
Usage:
After installation and validation done, can validate your custom written code by running below command, Run this command in same directory[magento-coding-standard/]:
1 |
vendor/bin/phpcs --standard=Magento2 app/code/[your module] |
It will take a few sec to complete the command and give results.
Auto fix issues:
Once you will get report you can see warnings and errors, there are many issues which you can fix auto just running by below shared command(phpcbf):
1 |
vendor/bin/phpcbf --standard=Magento2 app/code/[your module] |
In Conclusion:
If you follow this in your daily development process, it can stop you using deprecated functions and php coding violations. Your code will be clean and easily readable to everyone. Happy and clean coding!
Reference: