Writing clean and readable code is essential. Having a properly defined code style, and adhering to that, is tedious work. Let's automate it as much as possible.
Laravel code style
- Class names MUST be declared in
- Method names MUST be declared in
- Code MUST use 4 spaces for indenting, not tabs.
These are the obvious ones, some rules are more detailed and less easy to remember and stick to. It costs a lot of energy to memorize all rules and be strict about using them.
That is why automatic code style checkers are so great, they can save you a lot of work!
Many editors allow you to configure your preferred code style. My experience is that it is hard to configure and get exactly right. Also, I haven't found a predefined set of rules that works for me. That's why the following tools are so useful.
I've been happily using friendsofphp/php-cs-fixer for quite some time now. You can install it using Composer and it has a
.php_cs config file that you can commit to your repository.
.php_cs config is copied from
laravel/framework but I've excluded checking on some directories and files. It still uses the same fixers so the code style is exactly the same as the Laravel core.
php-cs-fixer fix to check and fix all issues in your repository!
Laravel Framework uses StyleCI to automatically check for code style issues on new commits and pull requests.
StyleCI allows you to deal with issues in multiple ways:
- It can notify you when it finds issues.
- It can automatically send (and merge) fixes through pull requests.
- It can automatically commit fixes.
Setup is easy with the .styleci.yml config file and they have Laravel code style preset. It's also free for open source projects!
How do you follow code style standards? Do you use different tools? What are your experiences? Feel free to leave a comment with your thoughts!