提升优化PHP代码质量的9个技巧

1.不要使用相对路径 经常会看到:  require_once('../../lib/some_class.php'); 该方法有不少缺点:
它首先查找指定的php包含路径, 而后查找当前目录. 所以会检查过多路径. 若是该脚本被另外一目录的脚本包含,
它的基本目录变成了另外一脚本所在的目录. 另外一问题, 当定时任务运行该脚本, 它的上级目录可能就不是工做目录了. 所以最佳选择是使用绝对路径:  
view urceprint?  define('ROOT' , '/var/www/project/');
 require_once(ROOT . '../../lib/some_class.php');  //rest of the code
咱们定义了一个绝对路径, 值被写死了. 咱们还能够改进它. 路径 /var/www/project 也可能会改变, 那么咱们每次都要改变它吗?
不是的, 咱们能够使用__FILE__常量, 如: //suppose your script is
/var/www/project/index.php  //Then__FILE__ will always have that full path.  javascript

define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
require_once(ROOT . '../../lib/some_class.php');  //rest of the code
如今, 不管你移到哪一个目录, 如移到一个外网的服务器上, 代码无须更改即可正确运行.  



2. 不要直接使用 require, include, include_once, required_once   能够在脚本头部引入多个文件,
像类库, 工具文件和助手函数等, 如: php

require_once('lib/Database.php'); 
require_once('lib/Mail.php');
require_once('helpers/utitlity_functions.php'); 这种用法至关原始. 应该更灵活点.
应编写个助手函数包含文件. 例如: css

function load_class($class_name)  {  //path to the class file  html

$path = ROOT . '/lib/' . $class_name . '.php';
 require_once( $path );  java

} mysql

 load_class('Database');  sql

load_class('Mail');
有什么不同吗? 该代码更具可读性.   將来你能够按需扩展该函数, 如:  shell

function load_class($class_name)  {  //path to the class file  数据库

$path = ROOT .'/lib/' . $class_name . '.php');  浏览器

if(file_exists($path))  {
 require_once( $path );  

  }

 }

还可作得更多: 为一样文件查找多个目录 能很容易的改变放置类文件的目录,
无须在代码各处一一修改 可以使用相似的函数加载文件, 如html内容.



3. 为应用保留调试代码 在开发环境中, 咱们打印数据库查询语句, 转存有问题的变量值, 而一旦问题解决, 咱们注释或删除它们.
然而更好的作法是保留调试代码. 在开发环境中, 你能够:

define('ENVIRONMENT' , 'development');
 if(! $db->query( $query )  {

   if(ENVIRONMENT == 'development')  {
 echo "$query failed";  

}  else  {

 echo "Database error. Please contact  administrator";  

}

 }

在服务器中, 你能够:

define('ENVIRONMENT' , 'production');
 if(! $db->query( $query )  {

 if(ENVIRONMENT == 'development')  {
 echo "$query failed";  

}  else  {

 echo "Database error. Please contact
administrator";  

}

 }



4. 使用可跨平台的函数执行命令 system, exec, passthru, shell_exec 这4个函数可用于执行系统命令.
每一个的行为都有细微差异. 问题在于, 当在共享主机中, 某些函数可能被选择性的禁用. 大多数新手趋于每次首先检查哪一个函数可用, 然而再使用它.  
更好的方案是封成函数一个可跨平台的函数.   /**  Method to execute a command in the terminal
 Uses :  1. system  2. passthru  3. exec  4. shell_exec  */  

function terminal($command)  {  //system  

if(function_exists('system'))  {
 ob_start();  system($command , $return_var);

 $output = ob_get_contents();

 ob_end_clean();  

}  //passthru  

else if(function_exists('passthru'))  {  

ob_start();  

passthru($command ,$return_var);  

$output = ob_get_contents();

 ob_end_clean();  

}  //exec  

else if(function_exists('exec'))  {
 exec($command , $output , $return_var);  

$output = implode("\n" , $output);  

}  //shell_exec  

else if(function_exists('shell_exec'))  {
 $output = shell_exec($command) ;  

}  else  {  

$output = 'Command execution not possible on this system';

 $return_var = 1;  

}

return array('output' => $output , 'status' => $return_var);  

}
 terminal('ls');

上面的函数將运行shell命令, 只要有一个系统函数可用, 这保持了代码的一致性.



5. 灵活编写函数

function add_to_cart($item_id , $qty)  {
 $_SESSION['cart']['item_id'] = $qty;  

}

add_to_cart( 'IPHONE3' , 2 );
使用上面的函数添加单个项目. 而当添加项列表的时候,你要建立另外一个函数吗? 不用, 只要稍加留意不一样类型的参数, 就会更灵活. 如:  
function add_to_cart($item_id , $qty)  {

 if(!is_array($item_id))  {
 $_SESSION['cart']['item_id'] = $qty;  

}  else  {  

foreach($item_id as $i_id => $qty)  {  

$_SESSION['cart']['i_id'] = $qty;

 }  

}  

}
 add_to_cart( 'IPHONE3' , 2 );  

add_to_cart( array('IPHONE3' => 2 , 'IPAD' => 5) );

如今, 同个函数能够处理不一样类型的输入参数了. 能够参照上面的例子重构你的多处代码, 使其更智能.



6. 有意忽略php关闭标签 我很想知道为何这么多关于php建议的博客文章都没提到这点. <?php  echo "Hello";
 //Now dont close this tag 这將节约你不少时间. 咱们举个例子:   一个super_class.php 文件  
<?php  

class super_class  {  

function super_function()  {  //super code  

}  

}  

?>  

//super extra character after the closing tag index.php

require_once('super_class.php');  //echo an image or pdf , or
set the cookies or session data 这样, 你將会获得一个 Headers already send error.
为何? 由于 “super extra character” 已经被输出了. 如今你得开始调试啦. 这会花费大量时间寻找 super
extra 的位置. 所以, 养成省略关闭符的习惯:

<?php  

class super_class  {

 function super_function()  {  

//super code

 }  

}

 //No closing tag 这会更好.



7. 在某地方收集全部输入, 一次输出给浏览器 这称为输出缓冲, 假如说你已在不一样的函数输出内容:

function print_header()  {  

echo "<div id='header'>Site Log and Login links</div>";  

}  

function print_footer()  {  

echo "<div id='footer'>Site was made by me</div>";  

}  

print_header();
 for($i = 0 ; $i < 100; $i++)  {  

echo "I is : $i <br />';  

}
print_footer();

替代方案, 在某地方集中收集输出. 你能够存储在函数的局部变量中,
也能够使用ob_start和ob_end_clean. 以下:  

function print_header()  {  

$o = "<div id='header'>Site Log and Login links</div>";  

return $o;  

}

function print_footer()  {  

$o = "<div id='footer'>Site was made by me</div>";  

return $o;  

}

echo print_header();  

for($i = 0 ; $i < 100; $i++)  {  

echo "I is : $i <br />';  

}

 echo print_footer();

为何须要输出缓冲:   >>能够在发送给浏览器前更改输出.

如 str_replaces 函数或多是 preg_replaces 或添加些监控/调试的html内容.   >>输出给浏览器的同时又作php的处理很糟糕.
你应该看到过有些站点的侧边栏或中间出现错误信息. 知道为何会发生吗? 由于处理和输出混合了.



8. 发送正确的mime类型头信息, 若是输出非html内容的话. 输出一些xml.   $xml = '<?xml
version="1.0" encoding="utf-8" standalone="yes"?>';  

$xml ="<response>  <code>0</code>  </response>"; //Send xml data  

echo $xml;

工做得不错. 但须要一些改进.

$xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';

 $xml = "<response>  <code>0</code>  </response>";
 //Send xml data  

header("content-type: text/xml");  

echo $xml;
注意header行. 该行告知浏览器发送的是xml类型的内容. 因此浏览器能正确的处理.不少的javascript库也依赖头信息. 相似的有
javascript , css, jpg image, png image:

JavaScript

header("content-type: application/x-javascript");  

echo "var a = 10";  

CSS
header("content-type: text/css");  

echo "#div id { background:#000; }";



9. 为mysql链接设置正确的字符编码   曾经遇到过在mysql表中设置了unicode/utf-8编码, phpadmin也能正确显示,
但当你获取内容并在页面输出的时候,会出现乱码. 这里的问题出在mysql链接的字符编码.  

//Attempt to connect to database  

$c = mysqli_connect($this->host , $this->username, $this->password);  //Check connection validity  

if (!$c)&nbsp;  { die ("Could not connect to the database host: <br />".mysqli_connect_error());  }  //Set the character set of the connection
if(!mysqli_set_charset ( $c , 'UTF8' ))  {  die('mysqli_set_charset() failed');  }

来源:http://www.68ecshop.com/article-1198.html

相关文章
相关标签/搜索