36计教您如何提高PHP代码质量

作者Silver Moon在binarytides上发表的一篇《40+ Techniques to enhance your php code》,文中主要探讨了如何提高PHP代码质量,供开发者学习与参考。

1.不要使用相对路径

常常会看到:

 
 
  1. require_once('../../lib/some_class.php'); 

该方法有很多缺点:

它首先查找指定的php包含路径, 然后查找当前目录.

因此会检查过多路径.

如果该脚本被另一目录的脚本包含, 它的基本目录变成了另一脚本所在的目录.

另一问题, 当定时任务运行该脚本, 它的上级目录可能就不是工作目录了.

因此最佳选择是使用绝对路径:

 
 
  1. define('ROOT' , '/var/www/project/');  
  2. require_once(ROOT . '../../lib/some_class.php');  
  3.        
  4. //rest of the code 

我们定义了一个绝对路径, 值被写死了. 我们还可以改进它. 路径 /var/www/project 也可能会改变, 那么我们每次都要改变它吗? 不是的, 我们可以使用__FILE__常量, 如:

 
 
  1. //suppose your script is /var/www/project/index.php  
  2. //Then __FILE__ will always have that full path.  
  3.        
  4. define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));  
  5. require_once(ROOT . '../../lib/some_class.php');  
  6.    
  7. //rest of the code 

现在, 无论你移到哪个目录, 如移到一个外网的服务器上, 代码无须更改便可正确运行.

2. 不要直接使用 require, include, include_once, required_once

可以在脚本头部引入多个文件, 像类库, 工具文件和助手函数等, 如:

 
 
  1. require_once('lib/Database.php');  
  2. require_once('lib/Mail.php');  
  3. require_once('helpers/utitlity_functions.php'); 

这种用法相当原始. 应该更灵活点. 应编写个助手函数包含文件. 例如:

 
 
  1. function load_class($class_name)  
  2. {  
  3.  //path to the class file  
  4.  $path = ROOT . '/lib/' . $class_name . '.php');  
  5.  require_once( $path );  
  6. }  
  7.        
  8. load_class('Database');  
  9. load_class('Mail'); 

有什么不一样吗? 该代码更具可读性.

將来你可以按需扩展该函数, 如:

 
 
  1. function load_class($class_name)  
  2. {  
  3.   //path to the class file  
  4.     $path = ROOT . '/lib/' . $class_name . '.php');  
  5.    
  6.   if(file_exists($path))  
  7.     {  
  8.  require_once( $path );  
  9.         }  

还可做得更多:

为同样文件查找多个目录

能很容易的改变放置类文件的目录, 无须在代码各处一一修改

可使用类似的函数加载文件, 如html内容.

3. 为应用保留调试代码

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

在开发环境中, 你可以:

 
 
  1. define('ENVIRONMENT' , 'development');  
  2.    
  3. if(! $db->query( $query )  
  4. {  
  5.    if(ENVIRONMENT == 'development')  
  6.    {  
  7.       echo "$query failed";  
  8.   }  
  9.    else  
  10.     {  
  11.        echo "Database error. Please contact administrator";  
  12.     }  

在服务器中, 你可以:

 
 
  1. define('ENVIRONMENT' , 'production');  
  2. if(! $db->query( $query )  
  3. {  
  4.    if(ENVIRONMENT == 'development')  
  5.    {  
  6.        echo "$query failed";  
  7.    }  
  8.     else  
  9.     {  
  10.         echo "Database error. Please contact administrator";  
  11.     }  

4. 使用可跨平台的函数执行命令

system, exec, passthru, shell_exec 这4个函数可用于执行系统命令. 每个的行为都有细微差别. 问题在于, 当在共享主机中, 某些函数可能被选择性的禁用. 大多数新手趋于每次首先检查哪个函数可用, 然而再使用它.

更好的方案是封成函数一个可跨平台的函数。

 
 
  1. 01  /**  
  2. 02      Method to execute a command in the terminal  
  3. 03      Uses :  
  4. 04     
  5. 05      1. system  
  6. 06      2. passthru  
  7. 07      3. exec  
  8. 08      4. shell_exec  
  9. 09     
  10. 10  */  
  11. 11  function terminal($command)  
  12. 12  {  
  13. 13      //system  
  14. 14      if(function_exists('system'))  
  15. 15      {  
  16. 16          ob_start();  
  17. 17          system($command , $return_var);  
  18. 18          $output = ob_get_contents();  
  19. 19          ob_end_clean();  
  20. 20      }  
  21. 21      //passthru  
  22. 22      else if(function_exists('passthru'))  
  23. 23      {  
  24. 24          ob_start();  
  25. 25          passthru($command , $return_var);  
  26. 26          $output = ob_get_contents();  
  27. 27          ob_end_clean();  
  28. 28      }  
  29. 29     
  30. 30      //exec  
  31. 31      else if(function_exists('exec'))  
  32. 32      {  
  33. 33          exec($command , $output , $return_var);  
  34. 34          $output = implode("\n" , $output);  
  35. 35      }  
  36. 36     
  37. 37      //shell_exec  
  38. 38      else if(function_exists('shell_exec'))  
  39. 39      {  
  40. 40          $output = shell_exec($command) ;  
  41. 41      }  
  42. 42     
  43. 43      else  
  44. 44      {  
  45. 45          $output = 'Command execution not possible on this system';  
  46. 46          $return_var = 1;  
  47. 47      }  
  48. 48     
  49. 49      return array('output' => $output , 'status' => $return_var);  
  50. 50  }  
  51. 51     
  52. 52  terminal('ls'); 

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

5. 灵活编写函数

 
 
  1. 1   function add_to_cart($item_id , $qty)  
  2. 2   {  
  3. 3       $_SESSION['cart']['item_id'] = $qty;  
  4. 4   }  
  5. 5      
  6. 6   add_to_cart( 'IPHONE3' , 2 ); 

使用上面的函数添加单个项目. 而当添加项列表的时候,你要创建另一个函数吗? 不用, 只要稍加留意不同类型的参数, 就会更灵活. 如:

 
 
  1. 01  function add_to_cart($item_id , $qty)  
  2. 02  {  
  3. 03      if(!is_array($item_id))  
  4. 04      {  
  5. 05          $_SESSION['cart']['item_id'] = $qty;  
  6. 06      }  
  7. 07     
  8. 08      else  
  9. 09      {  
  10. 10          foreach($item_id as $i_id => $qty)  
  11. 11          {  
  12. 12              $_SESSION['cart']['i_id'] = $qty;  
  13. 13          }  
  14. 14      }  
  15. 15  }  
  16. 16     
  17. 17  add_to_cart( 'IPHONE3' , 2 );  
  18. 18  add_to_cart( array('IPHONE3' => 2 , 'IPAD' => 5) ); 

现在, 同个函数可以处理不同类型的输入参数了. 可以参照上面的例子重构你的多处代码, 使其更智能.

6. 有意忽略php关闭标签

我很想知道为什么这么多关于php建议的博客文章都没提到这点.

 
 
  1. 1   <?php 
  2. 2      
  3. 3   echo "Hello";  
  4. 4      
  5. 5   //Now dont close this tag 

这將节约你很多时间. 我们举个例子:

一个 super_class.php 文件

 
 
  1. 01  <?php 
  2. 02  class super_class  
  3. 03  {  
  4. 04      function super_function()  
  5. 05      {  
  6. 06          //super code  
  7. 07      }  
  8. 08  }  
  9. 09  ?> 
  10. 10  //super extra character after the closing tag 

index.php

 
 
  1. 1   require_once('super_class.php');  
  2. 2      
  3. 3   //echo an image or pdf , or set the cookies or session data 

这样, 你將会得到一个 Headers already send error. 为什么? 因为 “super extra character” 已经被输出了. 现在你得开始调试啦. 这会花费大量时间寻找 super extra 的位置.

因此, 养成省略关闭符的习惯:

 
 
  1. 01  <?php 
  2. 02  class super_class  
  3. 03  {  
  4. 04      function super_function()  
  5. 05      {  
  6. 06          //super code  
  7. 07      }  
  8. 08  }  
  9. 09     
  10. 10  //No closing tag 

这会更好。

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

 
 
  1. 01  function print_header()  
  2. 02  {  
  3. 03      echo "<div id='header'>Site Log and Login links</div>";  
  4. 04  }  
  5. 05     
  6. 06  function print_footer()  
  7. 07  {  
  8. 08      echo "<div id='footer'>Site was made by me</div>";  
  9. 09  }  
  10. 10     
  11. 11  print_header();  
  12. 12  for($i = 0 ; $i < 100; $i++)  
  13. 13  {  
  14. 14      echo "I is : $i <br />';  
  15. 15  }  
  16. 16  print_footer(); 

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

 
 
  1. 01  function print_header()  
  2. 02  {  
  3. 03      $o = "<div id='header'>Site Log and Login links</div>";  
  4. 04      return $o;  
  5. 05  }  
  6. 06     
  7. 07  function print_footer()  
  8. 08  {  
  9. 09      $o = "<div id='footer'>Site was made by me</div>";  
  10. 10      return $o;  
  11. 11  }  
  12. 12     
  13. 13  echo print_header();  
  14. 14  for($i = 0 ; $i < 100; $i++)  
  15. 15  {  
  16. 16      echo "I is : $i <br />';  
  17. 17  }  
  18. 18  echo print_footer(); 

为什么需要输出缓冲:

>>可以在发送给浏览器前更改输出. 如 str_replaces 函数或可能是 preg_replaces 或添加些监控/调试的html内容.

>>输出给浏览器的同时又做php的处理很糟糕. 你应该看到过有些站点的侧边栏或中间出现错误信息. 知道为什么会发生吗? 因为处理和输出混合了.

8. 发送正确的mime类型头信息, 如果输出非html内容的话。

输出一些xml.

 
 
  1. 1   $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';  
  2. 2   $xml = "<response> 
  3. 3     <code>0</code> 
  4. 4   </response>";  
  5. 5      
  6. 6   //Send xml data  
  7. 7   echo $xml; 

工作得不错. 但需要一些改进.

 
 
  1. 1   $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';  
  2. 2   $xml = "<response> 
  3. 3     <code>0</code> 
  4. 4   </response>";  
  5. 5      
  6. 6   //Send xml data  
  7. 7   header("content-type: text/xml");  
  8. 8   echo $xml; 

注意header行. 该行告知浏览器发送的是xml类型的内容. 所以浏览器能正确的处理. 很多的javascript库也依赖头信息.

类似的有 javascript , css, jpg image, png image:

JavaScript

 
 
  1. 1   header("content-type: application/x-javascript");  
  2. 2   echo "var a = 10"; 

CSS

 
 
  1. 1   header("content-type: text/css");  
  2. 2   echo "#div id { background:#000; }"; 

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

 
 
  1. 01  //Attempt to connect to database  
  2. 02  $c = mysqli_connect($this->host , $this->username, $this->password);  
  3. 03     
  4. 04  //Check connection validity  
  5. 05  if (!$c)&nbsp;  
  6. 06  {  
  7. 07      die ("Could not connect to the database host: <br />". mysqli_connect_error());  
  8. 08  }  
  9. 09     
  10. 10  //Set the character set of the connection  
  11. 11  if(!mysqli_set_charset ( $c , 'UTF8' ))  
  12. 12  {  
  13. 13      die('mysqli_set_charset() failed');  
  14. 14  } 

一旦连接数据库, 最好设置连接的 characterset. 你的应用如果要支持多语言, 这么做是必须的.

10. 使用 htmlentities 设置正确的编码选项php5.4前, 字符的默认编码是ISO-8859-1, 不能直接输出如À â等.

 
 
  1. 1 $value = htmlentities($this->value , ENT_QUOTES , CHARSET);  

php5.4以后, 默认编码为UTF-8, 这將解决很多问题. 但如果你的应用是多语言的, 仍然要留意编码问题,.

11. 不要在应用中使用gzip压缩输出, 让apache处理考虑过使用 ob_gzhandler 吗? 不要那样做. 毫无意义. php只应用来编写应用. 不应操心服务器和浏览器的数据传输优化问题.

使用apache的mod_gzip/mod_deflate 模块压缩内容。

12. 使用json_encode输出动态javascript内容时常会用php输出动态javascript内容:

 
 
  1. 01  $images = array(  
  2. 02   'myself.png' , 'friends.png' , 'colleagues.png'  
  3. 03  );  
  4. 04     
  5. 05  $js_code = '';  
  6. 06     
  7. 07  foreach($images as $image)  
  8. 08  {  
  9. 09  $js_code ."'$image' ,";  
  10. 10  }  
  11. 11     
  12. 12  $js_code = 'var images = [' . $js_code . ']; ';  
  13. 13     
  14. 14  echo $js_code;  
  15. 15     
  16. 16  //Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; 

更聪明的做法, 使用 json_encode:

 
 
  1. 1   $images = array(  
  2. 2    'myself.png' , 'friends.png' , 'colleagues.png'  
  3. 3   );  
  4. 4      
  5. 5   $js_code = 'var images = ' . json_encode($images);  
  6. 6      
  7. 7   echo $js_code;  
  8. 8      
  9. 9   //Output is : var images = ["myself.png","friends.png","colleagues.png"] 

优雅乎?

13. 写文件前, 检查目录写权限写或保存文件前, 确保目录是可写的, 假如不可写, 输出错误信息. 这会节约你很多调试时间. linux系统中, 需要处理权限, 目录权限不当会导致很多很多的问题, 文件也有可能无法读取等等.

确保你的应用足够智能, 输出某些重要信息.

 
 
  1. 1   $contents = "All the content";  
  2. 2   $file_path = "/var/www/project/content.txt";  
  3. 3      
  4. 4   file_put_contents($file_path , $contents); 

这大体上正确. 但有些间接的问题. file_put_contents 可能会由于几个原因失败:

>>父目录不存在

>>目录存在, 但不可写

>>文件被写锁住?

所以写文件前做明确的检查更好.

 
 
  1. 01  $contents = "All the content";  
  2. 02  $dir = '/var/www/project';  
  3. 03  $file_path = $dir . "/content.txt";  
  4. 04     
  5. 05  if(is_writable($dir))  
  6. 06  {  
  7. 07      file_put_contents($file_path , $contents);  
  8. 08  }  
  9. 09  else  
  10. 10  {  
  11. 11      die("Directory $dir is not writable, or does not exist. Please check");  
  12. 12  } 

这么做后, 你会得到一个文件在何处写及为什么失败的明确信息.

14. 更改应用创建的文件权限在 linux环境中, 权限问题可能会浪费你很多时间. 从今往后, 无论何时, 当你创建一些文件后, 确保使用chmod设置正确权限. 否则的话, 可能文件先是由"php"用户创建, 但你用其它的用户登录工作, 系统將会拒绝访问或打开文件, 你不得不奋力获取root权限, 更改文件的权限等等.

 
 
  1. 1   // Read and write for owner, read for everybody else  
  2. 2   chmod("/somedir/somefile", 0644);  
  3. 3      
  4. 4   // Everything for owner, read and execute for others  
  5. 5   chmod("/somedir/somefile", 0755); 

15. 不要依赖submit按钮值来检查表单提交行为

 
 
  1. 1   if($_POST['submit'] == 'Save')  
  2. 2   {  
  3. 3       //Save the things  
  4. 4   } 

上面大多数情况正确, 除了应用是多语言的. 'Save' 可能代表其它含义. 你怎么区分它们呢. 因此, 不要依赖于submit按钮的值.

 
 
  1. 1   if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) )  
  2. 2   {  
  3. 3       //Save the things  
  4. 4   } 

现在你从submit按钮值中解脱出来了.

16. 为函数内总具有相同值的变量定义成静态变量

 
 
  1. 1   //Delay for some time  
  2. 2   function delay()  
  3. 3   {  
  4. 4       $sync_delay = get_option('sync_delay');  
  5. 5      
  6. 6       echo "<br />Delaying for $sync_delay seconds...";  
  7. 7       sleep($sync_delay);  
  8. 8       echo "Done <br />";  
  9. 9   } 

17. 不要直接使用 $_SESSION 变量

某些简单例子:

 
 
  1. 1 $_SESSION['username'] = $username;  
  2.  
  3. 2 $username = $_SESSION['username'];  
  4.  

这会导致某些问题. 如果在同个域名中运行了多个应用, session 变量可能会冲突. 两个不同的应用可能使用同一个session key. 例如, 一个前端门户, 和一个后台管理系统使用同一域名.

从现在开始, 使用应用相关的key和一个包装函数:

 
 
  1. 01  define('APP_ID' , 'abc_corp_ecommerce');  
  2. 02     
  3. 03  //Function to get a session variable  
  4. 04  function session_get($key)  
  5. 05  {  
  6. 06      $k = APP_ID . '.' . $key;  
  7. 07     
  8. 08      if(isset($_SESSION[$k]))  
  9. 09      {  
  10. 10          return $_SESSION[$k];  
  11. 11      }  
  12. 12     
  13. 13      return false;  
  14. 14  }  
  15. 15     
  16. 16  //Function set the session variable  
  17. 17  function session_set($key , $value)  
  18. 18  {  
  19. 19      $k = APP_ID . '.' . $key;  
  20. 20      $_SESSION[$k] = $value;  
  21. 21     
  22. 22      return true;  
  23. 23  } 

18. 將工具函数封装到类中

假如你在某文件中定义了很多工具函数:

 
 
  1. 01  function utility_a()  
  2. 02  {  
  3. 03      //This function does a utility thing like string processing  
  4. 04  }  
  5. 05     
  6. 06  function utility_b()  
  7. 07  {  
  8. 08      //This function does nother utility thing like database processing  
  9. 09  }  
  10. 10     
  11. 11  function utility_c()  
  12. 12  {  
  13. 13      //This function is ...  
  14. 14  } 

这些函数的使用分散到应用各处. 你可能想將他们封装到某个类中:

 
 
  1. 01  class Utility  
  2. 02  {  
  3. 03      public static function utility_a()  
  4. 04      {  
  5. 05     
  6. 06      }  
  7. 07     
  8. 08      public static function utility_b()  
  9. 09      {  
  10. 10     
  11. 11      }  
  12. 12     
  13. 13      public static function utility_c()  
  14. 14      {  
  15. 15     
  16. 16      }  
  17. 17  }  
  18. 18     
  19. 19  //and call them as  
  20. 20     
  21. 21  $a = Utility::utility_a();  
  22. 22  $b = Utility::utility_b(); 

显而易见的好处是, 如果php内建有同名的函数, 这样可以避免冲突.

另一种看法是, 你可以在同个应用中为同个类维护多个版本, 而不导致冲突. 这是封装的基本好处,无它。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值