良好的代码规范可以提高代码可读性,降低沟通成本,增加团队开发效率。
……
以上都是屁话,代码写得好看是为了自己享受,而不是没事自戳双眼。又不是要谈恋爱,搞个什么女为悦己者容做借口?
效果
废话不多说,先看效果(虽然前面动图已经展示过效果了):
使用前:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php namespace app\v1\service; use think\Model; class Register extends Model { public function register($username = null, $password = null, $extra = null) { $RegisterLogic = \think\Loader::model("Register", 'logic'); $rst = $RegisterLogic->register($data); return $rst; } } |
使用后:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php namespace app\v1\service; use think\Model; class Register extends Model { public function register($username = null, $password = null, $extra = null) { $RegisterLogic = \think\Loader::model('Register', 'logic'); $rst = $RegisterLogic->register($data); return $rst; } } |
多余的换行和缩进,错误的单引号双引号,都会被修正。
准备
- 主程序:Atom
- atom-beautify插件
- PHP 7
- PHP Coding Standards Fixer (PHP CS Fixer)
其中 PHP CS Fixer 可以从 Github 下载:https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases ,或是使用 Composer 或其它方式下载。注意 PHP CS Fixer 分为 1 和 2 两个大版本,使用区别很大。本文以新的 2 版本为例。
配置
本文以Win7平台下,Atom 1.21.2,atom-beautify 0.30.6 为例。先确保 Atom、atom-beautify插件、PHP 都正确安装了。
打开 atom-beautify 的 Setting。首先展开 Executables ,找到并展开 Executables 下的 PHP,配置 PHP 的绝对路径。之后展开下面的 PHP-CS-Fixer ,配置 PHP-CS-Fixer 文件的绝对路径。
之后继续向下找到 atom-beautify 下的 PHP ,配置 Default Beautifier 为 PHP-CS-Fixer ,配置 PHP-CS-Fixer Version 为 2 ,配置 Rules 为 @PSR2, @Symfony 。
(注:如果使用 PHP-CS-Fixer Version 1 ,则可以面配置 Rules )
使用
atom-beautify 的默认热键是 Ctrl+Alt+b ,找个未排版的 PHP 文件试一下就好了。注意如果 PHP 文件有语法错误是不能被美化的。
其他
atom-beautify 调用的 PHP-CS-Fixer ,其实和手工调用 PHP-CS-Fixer 没差。如果发现有不好用的地方,可以在命令行下自己测试一下,看看到底是 atom-beautify 的问题,还是 PHP-CS-Fixer 的问题。
近期评论