PHP, Coding Standards, and You
How stylish is the code you produce? I could further elaborate, but Wikipedia can do that for me.
Programming style refers to a set of rules or guidelines used when writing the source code for a computer program. It is often claimed that following a particular programming style will help programmers quickly read and understand source code conforming to the style as well as helping to avoid introducing faults.
Wikipedia on Programming style
Luckily, the PEAR project has already defined a comprehensive set of coding standards for the PHP language. Also, someone has already done the work of writing a validator for these standards in the form of PHP_CodeSniffer.
What follows are directions for installing and using PHP_CodeSniffer to check your own projects for coding standards violations.
Prerequisites
- A development machine with a web server and PHP5.
- The PEAR framework.
- A brain.
- 10 – 15 minutes.
Instructions
PHP_CodeSniffer can output errors and warnings in a variety of formats, but for our purposes we will use its xml output. However, xml is not the most readable format, so I wrote a php helper script to parse the xml and output styled xhtml.
First, download the php output formatter and save it somewhere as phpcs.php.
Hopefully your PHP installation came with PEAR, as we will need it for this next step. Open a terminal and run the PEAR package manager. On my development machine this is located at C:/xampp/php/pear.bat. With the help of the package manager, install PHP_CodeSniffer.
pear install PHP_CodeSniffer- Now we are going to run PHP_CodeSniffer on your project files. It might be helpful to save these commands in a batch file somewhere.
cd PROJECT_DIRECTORYPATH_TO_PHP_CODESNIFFER --tab-width=4 --report=xml . > phpcs.xml- Make sure that my phpcs.php file is in the same directory as the resulting phpcs.xml file, then load phpcs.php in the browser of your choice.
Tada!
Stay tuned for future improvements and editor integration, starting with my editor of choice, SciTE-st.