Coding standards vary greatly among developers. Even when writing the same code. And therein lies the problem. This becomes most evident when reviewing code that is not your own.
My own coding standards have changed over the years. As team lead, I drafted coding standards documents. This time, I wanted something active and easily adopted.
PHP coding standards
The PEAR coding standard is arguably the most prevalent among the PHP community. However, it is exhaustive and therefore not easily adopted. When reading about PHP namespacing last year, I came across the PHP Standard Requirements (PSR).
The latest version of this standard is PSR-2, which expands PSR-1, is a straightforward document outlining basic coding standards. It leaves some flexibility for developer style. And while I may not agree with every standard – mainly the curly brace conventions – it passes the governance.
Stick to the coding standards
It is human nature to bend the rules. But there’s no point in adopting a standard only to break it. I wanted to follow PSR-2 strictly. Not just the parts I liked. So I needed something to keep me honest.
A while back I came across PHP CodeSniffer. I intended to use it for automated code validation with an svn post-hook. PHP CodeSniffer features pluggable coding standards you can validate against. In addition, one for PSR-2 exist.
You can download PHP CodeSniffer. If you have PEAR installed, it’s easier:
pear install PHP_CodeSniffer
Verify PHP CodeSniffer with:
Note: If you receive warnings, your PHP
include_path likely does not include the PEAR directory. Check your PEAR installation to resolve this issue.
You can run PHP CodeSniffer against an entire directory.
phpcs --standard=PSR2 api/
Format legacy code
Since I just adopted the PSR-2 coding standard, I had several violations in my current projects. However, as traditional lazy developer, I didn’t want to edit hundreds of lines of code.
I found PHP CS Fixer. It auto-formats code to meet PSR-2 (among others). While it doesn’t correct everything, it fixes the tedious ones.
php-cs-fixer fix api/ --level=psr2 --dry-run
Note: I added
--dry-run for demonstration purposes. Remove it to update your files.
Go forth and be a better PHP developer
A good developer should follow a coding standard. While I am advocating PSR-2 here, it is really up to you. What matters is that you follow it strictly. Hopefully the tools above can help you do so.
This post is part of a series on How to be a Better PHP Developer.
comments powered by Disqus