When working on development, there are two things that I use on a daily basis: The CakePHP web framework and the PhpStorm IDE. Unfortunately PhpStorm has no “native” support for CakePHP yet (as it does for Symfony2 and Yii), although there is a pending issue that can still use more votes .
However, the latest PhpStorm 6.0 came with support for PHP Mess Detector and PHP Code Sniffer. The latter one also has an official CakePHP extension available, to inspect if your code meets the CakePHP defined coding standards. You can load the CakePHP template for Code Sniffer into PhpStorm and it will then highlight any code you have that does not comply with the Cake coding standards.
Neat, right? In order to get this up and running, you will need to complete some steps, which I will describe here. First of all, we will need the base package PHP_CodeSniffer. This is available through the PEAR repository. Just open up a command-line console and go to your PHP directory (unless the PHP binary is in your Environment variables (PATH), in which case it’ll work from any directory) and run:
pear install PHP_CodeSniffer
Now we have the base package, also retrieve the CakePHP template, so we can verify our code against the CakePHP standards. Run the following commands to obtain it:
pear channel-discover pear.cakephp.org pear install cakephp/CakePHP_CodeSniffer
OK, now we’re all set to integrate CakePHP CodeSniffer into our PhpStorm installation. Fire up the IDE and open a CakePHP project. Now open the Settings page (CTRL+ALT+S). Under the Project Settings, expand the PHP item and click Code Sniffer.
Here you must set the path to the PHP_CodeSniffer binary (or when on a Windows machine, it’s batch launcher). It should be installed in your PHP directory. You can verify that you have the correct binary selected by clicking the Validate button. It should show you the installed version of PHP_CodeSniffer.
Now that we have linked our Code Sniffer installation to our PhpStorm project, we still need to tell it to use the CakePHP template, so it will only raise “relevant” warnings. To do this, we stay in the Project Settings, but go the Inspections screen. Expand the PHP item and place a checkmark in front of the “PHP Code Sniffer validation” option. This will enable Code Sniffing in general, but still doesn’t enforce the Cake standards. To achieve this, we need to do one final step. After the “Coding standard” dropdown, click the refresh button. This will retrieve a list of all supported standards. CakePHP should be right at the top of it. Select it, click Apply and enjoy clean code!
If you also set the CakePHP Coding Standards under the Code Style settings, combining the Code Sniffer with the “Reformat Code” (CTRL+ALT+L) command in PhpStorm, you have very easy and powerful code refactoring tools.