PSR-2

具体内容查看http://www.php-fig.org/psr/psr-2/

phpcs

PHP Code Sniffer简称phpcs,用来检查你写的PHP是否符合PSR-2,若完全符合则没有任何结果,若有任何错误将显示错误报告。这适合帮我们检查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预设的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标准来修正我们的code。
--verbose表示PHP-CS-Fixer在执行时,会显示出详细的结果。

PhpStorm 配置

PhpStorm对于PSR-2有以下支持 :

原生支持PSR-2。
可外挂PHP Code Sniffer,让我在写code的同时就可提醒我们是否符合PSR-2。
可外挂PHP Coding Standards Fixer,将code修正为PSR-2。

1、设置使用PSR-2规范
Preferences -> Editor -> Code Style -> PHP : Set from… -> Predefined Style : PSR1/PSR2
\psr-2-1.png

还可以在psr-2的基础上继续设置自己的规则。

2、设置phpcs
A. Preferences -> Languages & Frameworks -> PHP -> Code Sniffer
\psr-2-2.png

PS:这里以我的phpcs路径为例:C:\Users\admin\AppData\Roaming\Composer\vendor\bin\phpcs.bat

B. Preferences -> Editor -> Inspections

将PHP Code Sniffer validation 打勾。
将Coding standard选PSR2。
\psr-2-3.png

3、php-cs-fixer
略(需要的话可以参照http://oomusou.io/php/php-psr2/


参考网站:


Laravel PSR-2

登陆发表评论