好的代码,就像一幅画,看着让人赏心悦目。有的时候因为要赶进度,代码也许就不会按照代码规范来写了,又要代码规范,又要速度,这是比较矛盾的。但是我们可以尽量让代码看着舒服一点。所以我推荐二种代码美化工具PHP Code Beautifier,PHP Beautifier
一,下载代码美化工具
PHP Code Beautifier下载,PHP Beautifier下载
二,以PHP Code Beautifier为例说一下用法
1,转换前的php代码
<?
function get_filetree($path){$tree = array();foreach(glob($path.'/*') as $single){if(is_dir($single)){
$tree = array_merge($tree,get_filetree($single));}else{if(substr($single,-3) == "php"){$tree[] = $single;}}}return $tree;}
$array = get_filetree($path);
?>
这种代码看着就想吐,可读性基本为0;
2,转换后的php代码
<?php
$path = '/tmp/test2'; //php的代码目录
function get_filetree($path){ //找出所有php文件
$tree = array();
foreach(glob($path.'/*') as $single){
if(is_dir($single)){
$tree = array_merge($tree,get_filetree($single));
}
else{
if(substr($single,-3) == "php"){
$tree[] = $single;
}
}
}
return $tree;
}
$array = get_filetree($path);
?>
结果如下:
Array
(
[0] => /tmp/test2/1.php
[1] => /tmp/test2/304.php
[2] => /tmp/test2/aaa.php
[3] => /tmp/test2/bbbb.php
[4] => /tmp/test2/face/face1.php
[5] => /tmp/test2/face/face2.php
)
这种代码看着就比较舒服了。
3,优化的方法如下
./phpCB --space-after-if \ --space-after-switch \ --space-after-while \ --space-before-start-angle-bracket \ --space-after-end-angle-bracket \ --one-true-brace-function-declaration \ --glue-amperscore \ --change-shell-comment-to-double-slashes-comment \ --force-large-php-code-tag \ --force-true-false-null-contant-lowercase \ --align-equal-statements \ --comment-rendering-style PEAR \ --equal-align-position 50 \ --padding-char-count 4 \ /tmp/test/mytest/test.php
关于--space-after-switch这类参数的设置,请参考http://blog.51yip.com/demo/phpcb/index.html,里面说的很清楚,并且每个参数都有实例,
4,批量优化php文件
foreach($array as $v){ //这里的数组就是前面产生的数组
$path_array = pathinfo($v);
$shell = "/tmp/test/mytest/phpCB/phpCB --space-after-if \
--space-after-switch \
--space-after-while \
--space-before-start-angle-bracket \
--space-after-end-angle-bracket \
--one-true-brace-function-declaration \
--glue-amperscore \
--change-shell-comment-to-double-slashes-comment \
--force-large-php-code-tag \
--force-true-false-null-contant-lowercase \
--align-equal-statements \
--comment-rendering-style PEAR \
--equal-align-position 50 \
--padding-char-count 4 \
".$v." > ".$path_array["dirname"]."/".$path_array["basename"]."_bak";
exec($shell,$array);
}
结果如下:
[root@krlcgcms01 test2]# tree
.
|-- 1.php
|-- 1.php_bak
|-- 304.php
|-- 304.php_bak
|-- aaa.php
|-- aaa.php_bak
|-- bbbb.php
|-- bbbb.php_bak
`-- face
|-- face1.php
|-- face1.php_bak
|-- face2.php
`-- face2.php_bak
如果怕影响原来的php文件,可以建立一个备份文件,等检查过后把.bak替换原来php文件,写个小脚本就可以了。
转载请注明
作者:海底苍鹰
地址:http://blog.51yip.com/php/1233.html
建议试试aStyle
aStyle能不能支持php?我在网上查了一下,冒似不支持php
我去试下..
太复杂了