One of the biggest problems I have found with PHP is the reputation that it gets. This is due to the amount of abuse that the language undergoes by many developers every day. They write code that works, and is efficient, but trying to figure out what it does can take hours as there are no comments, and the code is generally written in any old way. PHP is quite lenient with regards to how code is written.
This is where CodeSniffer comes in. CodeSniffer is a PHP5 script that goes through any PHP (or JavaScript) file that you give it and detects coding violations from a defined set of coding standards. These standards start out with the simple things like using spaces instead of tabs (due to the way in which tabs are displayed differently on different computers) to the more complex things like prefixing private variables with an underscore.
Because CodeSniffer is part of the PEAR framework you can install it using pear commands. As long as PEAR is installed you can use the following command to install CodeSniffer.
pear install PHP_CodeSniffer
If everything has worked you should find a file in your PHP folder called phpcs.bat. You can then use this file to run against your PHP scripts. Here is what to do if you want to run this file against a file.
phpcs class.MyClass.php
This produces something like the following output. I'm not going to reproduce it all as there are quite a few errors.
FILE: class.MyClass.php
--------------------------------------------------------------------------------
FOUND 165 ERROR(S) AND 35 WARNING(S) AFFECTING 123 LINE(S)
--------------------------------------------------------------------------------
1 | ERROR | End of line character is invalid; expected "\n" but found
| | "\r\n"
If you want to check an entire directory then just type in the path to the directory.
phpcs /path/to/file/
This will check each file in turn and produce output.
I thought I was pretty consistent with my coding, but after testing a simple 200 line class I found over 165 errors and 35 warnings for all sorts of things. The main complaint was my use of tabs instead of spaces, for which I can only blame my editor. However, there were a lot of other things such as aligning equals signs with equals signs on other lines.
Using this tool will help you write more understandable code, but will also spot certain syntax errors before they go live. It is good practice to use this tool on your code before you commit your changes as it can prevent you from making silly mistakes like leaving the semi-colon from the end of a line.
Comments
Thanks very nice article : )