PSR-2
具體內(nèi)容查看http://www.php-fig.org/psr/psr-2/
phpcs
PHP Code Sniffer簡稱phpcs,用來檢查你寫的PHP是否符合PSR-2,若完全符合則沒有任何結(jié)果,若有任何錯誤將顯示錯誤報告。這適合幫我們檢查Legacy PHP是否符合PSR-2。
1、安裝
composer global require 'squizlabs/php_codesniffer=*'
Changed current directory to /home/vagrant/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
- Installing squizlabs/php_codesniffer (2.3.4)
Downloading: 100%
Writing lock file
Generating autoload files
2、測試
phpcs --version
PHP_CodeSniffer version 2.3.4 (stable) by Squiz (http://www.squiz.net)
3、檢查PSR-2
phpcs --standard=PSR2 Laravel/app
Laravel為你的項目名稱,因為我們寫的code都在app目錄下,所以直接指定PHP Code Sniffer幫我們檢查app目錄下所有的.php文件。
PHP Code Sniffer預(yù)設(shè)的coding style為PEAR,因為我們用的是PSR-2,所以要特別使用加上--standard=PSR2。
php-cs-fixer
PHP Coding Standards Fixer簡稱php-cs-fixer。雖然PHP Code Sniffer可以幫我們找出哪些code不符合PSR-2,若只有幾個文件,我們手動改就可以,若文件太多,就得依賴php-cs-fixer幫我們修正。
1、安裝
composer global require fabpot/php-cs-fixer
Changed current directory to /home/vagrant/.composer
Using version ^1.10 for fabpot/php-cs-fixer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
- Installing sebastian/diff (1.3.0)
Downloading: 100%
- Installing symfony/stopwatch (v2.7.4)
Downloading: 100%
- Installing symfony/finder (v2.7.4)
Downloading: 100%
- Installing symfony/filesystem (v2.7.4)
Downloading: 100%
- Installing symfony/event-dispatcher (v2.7.4)
Downloading: 100%
- Installing fabpot/php-cs-fixer (v1.10)
Downloading: 100%
symfony/event-dispatcher suggests installing symfony/dependency-injection ()
symfony/event-dispatcher suggests installing symfony/http-kernel ()
Writing lock file
Generating autoload files
2、測試
php-cs-fixer --version
PHP CS Fixer version 1.10 by Fabien Potencier
3、修正PSR-2
php-cs-fixer fix Laravel/app/ --level=psr2 --verbose
Laravel為你的項目名稱,因為我們寫的code都在app目錄下,所以直接指定PHP-CS-Fixer幫我們檢查app目錄下所有的.php文件。
--level=psr2指定使用PSR-2標(biāo)準(zhǔn)來修正我們的code。
--verbose表示PHP-CS-Fixer在執(zhí)行時,會顯示出詳細(xì)的結(jié)果。
PhpStorm 配置
PhpStorm對于PSR-2有以下支持 :
原生支持PSR-2。
可外掛PHP Code Sniffer,讓我在寫code的同時就可提醒我們是否符合PSR-2。
可外掛PHP Coding Standards Fixer,將code修正為PSR-2。
1、設(shè)置使用PSR-2規(guī)范
Preferences -> Editor -> Code Style -> PHP : Set from… -> Predefined Style : PSR1/PSR2

還可以在psr-2的基礎(chǔ)上繼續(xù)設(shè)置自己的規(guī)則。
2、設(shè)置phpcs
A. Preferences -> Languages & Frameworks -> PHP -> Code Sniffer

PS:這里以我的phpcs路徑為例:C:\Users\admin\AppData\Roaming\Composer\vendor\bin\phpcs.bat
B. Preferences -> Editor -> Inspections
將PHP Code Sniffer validation 打勾。
將Coding standard選PSR2。

3、php-cs-fixer
略(需要的話可以參照http://oomusou.io/php/php-psr2/)
參考網(wǎng)站: