PHP, Coding Standards, and You

tags: ,

How styl­ish is the code you pro­duce? I could fur­ther elab­o­rate, but Wikipedia can do that for me.

Pro­gram­ming style refers to a set of rules or guide­lines used when writ­ing the source code for a com­puter pro­gram. It is often claimed that fol­low­ing a par­tic­u­lar pro­gram­ming style will help pro­gram­mers quickly read and under­stand source code con­form­ing to the style as well as help­ing to avoid intro­duc­ing faults.

Wikipedia on Pro­gram­ming style

Luck­ily, the PEAR project has already defined a com­pre­hen­sive set of cod­ing stan­dards for the PHP lan­guage. Also, some­one has already done the work of writ­ing a val­ida­tor for these stan­dards in the form of PHP_​CodeSniffer.

What fol­lows are direc­tions for installing and using PHP_​CodeSniffer to check your own projects for cod­ing stan­dards violations.

Pre­req­ui­sites

Instruc­tions

PHP_​CodeSniffer can out­put errors and warn­ings in a vari­ety of for­mats, but for our pur­poses we will use its xml out­put. How­ever, xml is not the most read­able for­mat, so I wrote a php helper script to parse the xml and out­put styled xhtml.

  1. First, down­load the php out­put for­mat­ter and save it some­where as phpcs.php.

  2. Hope­fully your PHP instal­la­tion came with PEAR, as we will need it for this next step. Open a ter­mi­nal and run the PEAR pack­age man­ager. On my devel­op­ment machine this is located at C:/xampp/php/pear.bat. With the help of the pack­age man­ager, install PHP_​CodeSniffer.

pear install PHP_CodeSniffer
  1. Now we are going to run PHP_​CodeSniffer on your project files. It might be help­ful to save these com­mands in a batch file somewhere.
cd PROJECT_DIRECTORY
PATH_TO_PHP_CODESNIFFER --tab-width=4 --report=xml . > phpcs.xml
  1. Make sure that my phpcs.php file is in the same direc­tory as the result­ing phpcs.xml file, then load phpcs.php in the browser of your choice.

Tada!

Stay tuned for future improve­ments and edi­tor inte­gra­tion, start­ing with my edi­tor of choice, SciTE-​st.

Feedback