PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 20 ■ CONTINUOUS INTEGRATION

Coding Standards


I can argue all day about the best place to put a brace, whether to indent with tabs or spaces, how to
name a private property variable. Wouldn’t it be nice if I could enforce my prejudices with a tool? Thanks
to PHP_CodeSniffer I can. CodeSniffer can apply one of a set of coding standards to a project and
generate a report, telling you just how bad your style is.
That might sound like a massive pain in the rear end. In fact, it can be just that. But there are
sensible non-passive aggressive uses for a tool like this. I’ll get to these, but first I’ll put the tool through
its paces. Installation first:


$ sudo pear install PHP_CodeSniffer


Now I’m going to apply the Zend coding standard to my code:

$ phpcs --standard=Zend userthing/persist/UserStore.php


FILE: ...userthing/src/userthing/persist/UserStore.php


FOUND 10 ERROR(S) AND 0 WARNING(S) AFFECTING 8 LINE(S)


6 | ERROR | Opening brace of a class must be on the line after the definition
7 | ERROR | Private member variable "users" must contain a leading underscore
9 | ERROR | Opening brace should be on a new line
13 | ERROR | Multi-line function call not indented correctly; expected 12
| | spaces but found 16
...


Clearly, I’d have to adjust my style to submit code to Zend!
It makes sense however, for a team to define coding guidelines. In fact, the decision as to which set
of rules you choose is probably less important than the decision to abide by a common standard in the
first place. If a codebase is consistent, then it’s easier to read, and therefore easier to work with. Naming
conventions, for example, can help to clarify the purpose of variables or properties.
Coding conventions can play a role in reducing risky or bug-prone code as well.
This is a dangerous area, though. Some style decisions are highly subjective, and people can be
disproportionately defensive about their way of doing things. CodeSniffer allows you to define your own
rules, so I suggest that you get buy in from your team on a set of rules so that no one feels that their
coding life has become a coding nightmare.
Another benefit of an automated tool is its impersonal nature. If your team does decide to impose a
set of coding conventions, it’s arguably better having a humorless script correcting your style, than a
humorless co-worker doing the same thing.


PHP Code Browser


You may be wedded to your exciting IDE or, like me, you might prefer to edit with vi. Either way,
when you’re looking at a report that tells you your style is lousy, or, more important, trying to
understand a failed test, it’s good to be able to pull up the code right away. The PHP_CodeBrowser
package lets you do just that.
This is bleeding-edge code, so to install you need to tell PEAR that you’re ready to accept an alpha
release.


$ sudo pear config-set preferred_state alpha

Free download pdf