提升優化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

相關文章
相關標籤/搜索