What Is PHP CS Fixer and How It Can Help You Keep Your Code Cleaner
3 min read
What is PHP CS Fixer
PHP CS Fixer stands for PHP Coding Standards Fixer. This is a tool that fixes your code to follow standards. There are various PHP coding standards that you can follow, such as the popular PSR-1, and PSR-12 published by the PHP Framework Interoperability Group (the full list of PSR standards can be found here).
There are also other community-driven standards like the Symphony.
Manually fixing coding standards in your code is a very tedious process, so PHP CS Fixer is a great solution. It helps you and your team ensure that you all follow the same rules when writing code, thus keeping it cleaner.
The recommended way to install PHP CS Fixer is to use Composer in a dedicated directory in your project, for example in the
mkdir --parents tools/php-cs-fixer composer require --working-dir=tools/php-cs-fixer friendsofphp/php-cs-fixer
For more details and other installation methods, see installation instructions.
Usage: Option 1
Assuming you installed PHP CS Fixer as instructed above, you can run the following command to fix the files PHP files in the
tools/php-cs-fixer/vendor/bin/php-cs-fixer fix src
See usage, list of built-in rules, list of rule sets, and configuration file documentation for more details. If you need to apply code styles that are not supported by the tool, you can create custom rules.
Usage: Option 2 (Editor Integration)
However, executing a command manually does not seem to be a convenient approach. I personally prefer to run PHP CS Fixer by pressing a pre-configured keyboard shortcut in PHP Storm.
You can configure PHP CS Fixer for various code editors as described below:
Usage: Option 3 (Run PHP CS Fixer on every commit)
As an alternative option, you can fix your code on every commit using Husky and lint-staged. Using these tools PHP CS Fixer will run on your staged files, in other words, on the files you want to commit. Here is a great article explaining how to set up these tools to work with PHP CS Fixer.
Easy way of configuring PHP CS Fixer
If you are new to PHP Coding Standards and want to quickly configure PHP CS Fixer, I highly recommend using PHP CS Fixer Configurator by Michele Locati. It has a pre-defined set of rules that you can select and create your own configuration.
Most rules, when clicked, will display general information about the rule, available configuration options, and usage examples. The PHP CS Fixer configuration file generated by this tool can be exported to use in your project and then imported again in case you want to do some modifications.
The end. I hope you found this information helpful, stay tuned for more content! :)
Did you find this article valuable?
Support Andrew Savetchuk by becoming a sponsor. Any amount is appreciated!