自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

提高PHP代碼質(zhì)量36計(jì)

開發(fā) 后端
本文詳細(xì)的介紹了PHP代碼的一些優(yōu)點(diǎn)和缺點(diǎn),以及編寫代碼更多的方法,希望能給網(wǎng)友們在代碼質(zhì)量這方面能有所提高。詳細(xì)請看下文

1.不要使用相對路徑

常常會看到: 

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

該方法有很多缺點(diǎn):

它首先查找指定的php包含路徑, 然后查找當(dāng)前目錄.

因此會檢查過多路徑.

如果該腳本被另一目錄的腳本包含, 它的基本目錄變成了另一腳本所在的目錄.

另一問題, 當(dāng)定時(shí)任務(wù)運(yùn)行該腳本, 它的上級目錄可能就不是工作目錄了.

因此***選擇是使用絕對路徑:

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

我們定義了一個絕對路徑, 值被寫死了. 我們還可以改進(jìn)它. 路徑 /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 

現(xiàn)在, 無論你移到哪個目錄, 如移到一個外網(wǎng)的服務(wù)器上, 代碼無須更改便可正確運(yùn)行.

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

可以在腳本頭部引入多個文件, 像類庫, 工具文件和助手函數(shù)等, 如: 

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

這種用法相當(dāng)原始. 應(yīng)該更靈活點(diǎn). 應(yīng)編寫個助手函數(shù)包含文件. 例如:

  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'); 

有什么不一樣嗎? 該代碼更具可讀性.

將來你可以按需擴(kuò)展該函數(shù), 如:

  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.     }  

還可做得更多:

為同樣文件查找多個目錄

能很容易的改變放置類文件的目錄, 無須在代碼各處一一修改

可使用類似的函數(shù)加載文件, 如html內(nèi)容.

3. 為應(yīng)用保留調(diào)試代碼

在開發(fā)環(huán)境中, 我們打印數(shù)據(jù)庫查詢語句, 轉(zhuǎn)存有問題的變量值, 而一旦問題解決, 我們注釋或刪除它們. 然而更好的做法是保留調(diào)試代碼.

在開發(fā)環(huán)境中, 你可以:

  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.     }  

在服務(wù)器中, 你可以:

  1. define('ENVIRONMENT' , 'production');  
  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.     }  

4. 使用可跨平臺的函數(shù)執(zhí)行命令

system, exec, passthru, shell_exec 這4個函數(shù)可用于執(zhí)行系統(tǒng)命令. 每個的行為都有細(xì)微差別. 問題在于, 當(dāng)在共享主機(jī)中, 某些函數(shù)可能被選擇性的禁用. 大多數(shù)新手趨于每次首先檢查哪個函數(shù)可用, 然而再使用它.

更好的方案是封成函數(shù)一個可跨平臺的函數(shù). 

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

上面的函數(shù)將運(yùn)行shell命令, 只要有一個系統(tǒng)函數(shù)可用, 這保持了代碼的一致性. 

5. 靈活編寫函數(shù)

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

使用上面的函數(shù)添加單個項(xiàng)目. 而當(dāng)添加項(xiàng)列表的時(shí)候,你要創(chuàng)建另一個函數(shù)嗎? 不用, 只要稍加留意不同類型的參數(shù), 就會更靈活. 如:

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

現(xiàn)在, 同個函數(shù)可以處理不同類型的輸入?yún)?shù)了. 可以參照上面的例子重構(gòu)你的多處代碼, 使其更智能.

6. 有意忽略php關(guān)閉標(biāo)簽

我很想知道為什么這么多關(guān)于php建議的博客文章都沒提到這點(diǎn).

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

這將節(jié)約你很多時(shí)間. 我們舉個例子:

一個 super_class.php 文件

  1. <?php  
  2. class super_class  
  3. {  
  4.     function super_function()  
  5.     {  
  6.         //super code  
  7.     }  
  8. }  
  9. ?>  
  10. //super extra character after the closing tag 

index.php

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

這樣, 你將會得到一個 Headers already send error. 為什么? 因?yàn)?nbsp;“super extra character” 已經(jīng)被輸出了. 現(xiàn)在你得開始調(diào)試?yán)? 這會花費(fèi)大量時(shí)間尋找 super extra 的位置.

因此, 養(yǎng)成省略關(guān)閉符的習(xí)慣:

  1. <?php  
  2. class super_class  
  3. {  
  4.     function super_function()  
  5.     {  
  6.         //super code  
  7.     }  
  8. }  
  9.  
  10. //No closing tag 

這會更好. 

7. 在某地方收集所有輸入, 一次輸出給瀏覽器

這稱為輸出緩沖, 假如說你已在不同的函數(shù)輸出內(nèi)容:

  1. function print_header()  
  2. {  
  3.     echo "<div id='header'>Site Log and Login links</div>";  
  4. }  
  5.  
  6. function print_footer()  
  7. {  
  8.     echo "<div id='footer'>Site was made by me</div>";  
  9. }  
  10.  
  11. print_header();  
  12. for($i = 0 ; $i < 100; $i++)  
  13. {  
  14.     echo "I is : $i <br />';  
  15. }  
  16. print_footer(); 
替代方案, 在某地方集中收集輸出. 你可以存儲在函數(shù)的局部變量中, 也可以使用ob_start和ob_end_clean. 如下:
  1. function print_header()  
  2. {  
  3.     $o = "<div id='header'>Site Log and Login links</div>";  
  4.     return $o;  
  5. }  
  6.  
  7. function print_footer()  
  8. {  
  9.     $o = "<div id='footer'>Site was made by me</div>";  
  10.     return $o;  
  11. }  
  12.  
  13. echo print_header();  
  14. for($i = 0 ; $i < 100; $i++)  
  15. {  
  16.     echo "I is : $i <br />';  
  17. }  
  18. echo print_footer(); 

為什么需要輸出緩沖:

>>可以在發(fā)送給瀏覽器前更改輸出. 如 str_replaces 函數(shù)或可能是 preg_replaces 或添加些監(jiān)控/調(diào)試的html內(nèi)容.

>>輸出給瀏覽器的同時(shí)又做php的處理很糟糕. 你應(yīng)該看到過有些站點(diǎn)的側(cè)邊欄或中間出現(xiàn)錯誤信息. 知道為什么會發(fā)生嗎? 因?yàn)樘幚砗洼敵龌旌狭?

8. 發(fā)送正確的mime類型頭信息, 如果輸出非html內(nèi)容的話.

輸出一些xml.

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

工作得不錯. 但需要一些改進(jìn).

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

注意header行. 該行告知瀏覽器發(fā)送的是xml類型的內(nèi)容. 所以瀏覽器能正確的處理. 很多的javascript庫也依賴頭信息.

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

JavaScript

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

CSS

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

9. 為mysql連接設(shè)置正確的字符編碼

曾經(jīng)遇到過在mysql表中設(shè)置了unicode/utf-8編碼,  phpadmin也能正確顯示, 但當(dāng)你獲取內(nèi)容并在頁面輸出的時(shí)候,會出現(xiàn)亂碼. 這里的問題出在mysql連接的字符編碼.

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

一旦連接數(shù)據(jù)庫, ***設(shè)置連接的 characterset. 你的應(yīng)用如果要支持多語言, 這么做是必須的.

10. 使用 htmlentities 設(shè)置正確的編碼選項(xiàng)

php5.4前, 字符的默認(rèn)編碼是ISO-8859-1, 不能直接輸出如À â等.

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

php5.4以后, 默認(rèn)編碼為UTF-8, 這將解決很多問題. 但如果你的應(yīng)用是多語言的, 仍然要留意編碼問題,.

11. 不要在應(yīng)用中使用gzip壓縮輸出, 讓apache處理

考慮過使用 ob_gzhandler 嗎? 不要那樣做. 毫無意義. php只應(yīng)用來編寫應(yīng)用. 不應(yīng)操心服務(wù)器和瀏覽器的數(shù)據(jù)傳輸優(yōu)化問題.

使用apache的mod_gzip/mod_deflate 模塊壓縮內(nèi)容.

12. 使用json_encode輸出動態(tài)javascript內(nèi)容

時(shí)常會用php輸出動態(tài)javascript內(nèi)容:

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

更聰明的做法, 使用 json_encode:

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

優(yōu)雅乎?

13. 寫文件前, 檢查目錄寫權(quán)限

寫或保存文件前, 確保目錄是可寫的, 假如不可寫, 輸出錯誤信息. 這會節(jié)約你很多調(diào)試時(shí)間. linux系統(tǒng)中, 需要處理權(quán)限, 目錄權(quán)限不當(dāng)會導(dǎo)致很多很多的問題, 文件也有可能無法讀取等等.

確保你的應(yīng)用足夠智能, 輸出某些重要信息.

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

這大體上正確. 但有些間接的問題. file_put_contents 可能會由于幾個原因失敗:

>>父目錄不存在

>>目錄存在, 但不可寫

>>文件被寫鎖住?

所以寫文件前做明確的檢查更好.

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

這么做后, 你會得到一個文件在何處寫及為什么失敗的明確信息.

14. 更改應(yīng)用創(chuàng)建的文件權(quán)限

在 linux環(huán)境中, 權(quán)限問題可能會浪費(fèi)你很多時(shí)間. 從今往后, 無論何時(shí), 當(dāng)你創(chuàng)建一些文件后, 確保使用chmod設(shè)置正確權(quán)限. 否則的話, 可能文件先是由"php"用戶創(chuàng)建, 但你用其它的用戶登錄工作, 系統(tǒng)將會拒絕訪問或打開文件, 你不得不奮力獲取root權(quán)限,  更改文件的權(quán)限等等.

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

15. 不要依賴submit按鈕值來檢查表單提交行為

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

上面大多數(shù)情況正確, 除了應(yīng)用是多語言的. 'Save' 可能代表其它含義. 你怎么區(qū)分它們呢. 因此, 不要依賴于submit按鈕的值.

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

現(xiàn)在你從submit按鈕值中解脫出來了.

16. 為函數(shù)內(nèi)總具有相同值的變量定義成靜態(tài)變量

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

用靜態(tài)變量取代:

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

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

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

這會導(dǎo)致某些問題. 如果在同個域名中運(yùn)行了多個應(yīng)用, session 變量可能會沖突. 兩個不同的應(yīng)用可能使用同一個session key. 例如, 一個前端門戶, 和一個后臺管理系統(tǒng)使用同一域名.

從現(xiàn)在開始, 使用應(yīng)用相關(guān)的key和一個包裝函數(shù):

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

18. 將工具函數(shù)封裝到類中

假如你在某文件中定義了很多工具函數(shù):

  1. function utility_a()  
  2. {  
  3.     //This function does a utility thing like string processing  
  4. }  
  5.  
  6. function utility_b()  
  7. {  
  8.     //This function does nother utility thing like database processing  
  9. }  
  10.  
  11. function utility_c()  
  12. {  
  13.     //This function is ...  

這些函數(shù)的使用分散到應(yīng)用各處. 你可能想將他們封裝到某個類中:

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

顯而易見的好處是, 如果php內(nèi)建有同名的函數(shù), 這樣可以避免沖突.

另一種看法是, 你可以在同個應(yīng)用中為同個類維護(hù)多個版本, 而不導(dǎo)致沖突. 這是封裝的基本好處, 無它.

19. Bunch of silly tips 

>>使用echo取代print

>>使用str_replace取代preg_replace, 除非你絕對需要

>>不要使用 short tag

>>簡單字符串用單引號取代雙引號

>>head重定向后記得使用exit

>>不要在循環(huán)中調(diào)用函數(shù)

>>isset比strlen快

>>始中如一的格式化代碼

>>不要刪除循環(huán)或者if-else的括號

不要這樣寫代碼:

  1. <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">if($a == true) $a_count++;</span> 

這絕對WASTE.

寫成:

  1. <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">if($a == true)  
  2. {  
  3.     $a_count++;  
  4. }</span> 

不要嘗試省略一些語法來縮短代碼. 而是讓你的邏輯簡短.

>>使用有高亮語法顯示的文本編輯器. 高亮語法能讓你減少錯誤.

20. 使用array_map快速處理數(shù)組

比如說你想 trim 數(shù)組中的所有元素. 新手可能會:

  1. foreach($arr as $c => $v)  
  2. {  
  3.     $arr[$c] = trim($v);  

但使用 array_map 更簡單:

  1. $arr = array_map('trim' , $arr); 

這會為$arr數(shù)組的每個元素都申請調(diào)用trim. 另一個類似的函數(shù)是 array_walk. 請查閱文檔學(xué)習(xí)更多技巧.

21. 使用 php filter 驗(yàn)證數(shù)據(jù)

你肯定曾使用過正則表達(dá)式驗(yàn)證 email , ip地址等. 是的,每個人都這么使用. 現(xiàn)在, 我們想做不同的嘗試, 稱為filter.

php的filter擴(kuò)展提供了簡單的方式驗(yàn)證和檢查輸入.

22. 強(qiáng)制類型檢查

  1. $amount = intval$_GET['amount'] );  
  2. $rate = (int) $_GET['rate']; 

這是個好習(xí)慣.

23. 如果需要,使用profiler如xdebug

如果你使用php開發(fā)大型的應(yīng)用, php承擔(dān)了很多運(yùn)算量, 速度會是一個很重要的指標(biāo). 使用profile幫助優(yōu)化代碼. 可使用

xdebug和webgrid.

24. 小心處理大數(shù)組

對于大的數(shù)組和字符串, 必須小心處理. 常見錯誤是發(fā)生數(shù)組拷貝導(dǎo)致內(nèi)存溢出,拋出Fat

  1. $db_records_in_array_format//This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB  
  2.  
  3. $cc = $db_records_in_array_format//2MB more  
  4.  
  5. some_function($cc); //Another 2MB ? 

 

當(dāng)導(dǎo)入或?qū)С鯿sv文件時(shí), 常常會這么做.

不要認(rèn)為上面的代碼會經(jīng)常因內(nèi)存限制導(dǎo)致腳本崩潰. 對于小的變量是沒問題的, 但處理大數(shù)組的時(shí)候就必須避免.

確保通過引用傳遞, 或存儲在類變量中:

  1. $a = get_large_array();  
  2. pass_to_function(&$a); 

這么做后,向函數(shù)傳遞變量引用(而不是拷貝數(shù)組). 查看文檔.

  1. class A  
  2. {  
  3.     function first()  
  4.     {  
  5.         $this->a = get_large_array();  
  6.         $this->pass_to_function();  
  7.     }  
  8.  
  9.     function pass_to_function()  
  10.     {  
  11.         //process $this->a  
  12.     }  

盡快的 unset 它們, 讓內(nèi)存得以釋放,減輕腳本負(fù)擔(dān).

25.  由始至終使用單一數(shù)據(jù)庫連接

確保你的腳本由始至終都使用單一的數(shù)據(jù)庫連接. 在開始處正確的打開連接, 使用它直到結(jié)束, ***關(guān)閉它. 不要像下面這樣在函數(shù)中打開連接:

  1. function add_to_cart()  
  2. {  
  3.     $db = new Database();  
  4.     $db->query("INSERT INTO cart .....");  
  5. }  
  6.  
  7. function empty_cart()  
  8. {  
  9.     $db = new Database();  
  10.     $db->query("DELETE FROM cart .....");  

使用多個連接是個糟糕的, 它們會拖慢應(yīng)用, 因?yàn)閯?chuàng)建連接需要時(shí)間和占用內(nèi)存.

特定情況使用單例模式, 如數(shù)據(jù)庫連接.

26. 避免直接寫SQL, 抽象之

不厭其煩的寫了太多如下的語句:

  1. <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">$query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";  
  2. $db->query($query); //call to mysqli_query()</span> 

這不是個建壯的方案. 它有些缺點(diǎn):

>>每次都手動轉(zhuǎn)義值

>>驗(yàn)證查詢是否正確

>>查詢的錯誤會花很長時(shí)間識別(除非每次都用if-else檢查)

>>很難維護(hù)復(fù)雜的查詢

因此使用函數(shù)封裝:

  1. <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">function insert_record($table_name , $data)  
  2. {  
  3.     foreach($data as $key => $value)  
  4.     {  
  5.     //mysqli_real_escape_string  
  6.         $data[$key] = $db->mres($value);  
  7.     }  
  8.  
  9.     $fields = implode(',' , array_keys($data));  
  10.     $values = "'" . implode("','" , array_values($data)) . "'";  
  11.  
  12.     //Final query  
  13.     $query = "INSERT INTO {$table}($fields) VALUES($values)";  
  14.  
  15.     return $db->query($query);  
  16. }  
  17.  
  18. $data = array('name' => $name , 'email' => $email  , 'address' => $address , 'phone' => $phone);  
  19.  
  20. insert_record('users' , $data);</span> 

看到了嗎? 這樣會更易讀和擴(kuò)展. record_data 函數(shù)小心的處理了轉(zhuǎn)義. 

***的優(yōu)點(diǎn)是數(shù)據(jù)被預(yù)處理為一個數(shù)組, 任何語法錯誤都會被捕獲.

該函數(shù)應(yīng)該定義在某個database類中, 你可以像 $db->insert_record這樣調(diào)用.

查看本文, 看看怎樣讓你處理數(shù)據(jù)庫更容易.

類似的也可以編寫update,select,delete方法. 試試吧.

27. 將數(shù)據(jù)庫生成的內(nèi)容緩存到靜態(tài)文件中

如果所有的內(nèi)容都是從數(shù)據(jù)庫獲取的, 它們應(yīng)該被緩存. 一旦生成了, 就將它們保存在臨時(shí)文件中. 下次請求該頁面時(shí), 可直接從緩存中取, 不用再查數(shù)據(jù)庫.

好處:

>>節(jié)約php處理頁面的時(shí)間, 執(zhí)行更快

>>更少的數(shù)據(jù)庫查詢意味著更少的mysql連接開銷

28. 在數(shù)據(jù)庫中保存sessio-

base 標(biāo)簽非常有用. 假設(shè)你的應(yīng)用分成幾個子目錄, 它們都要包括相同的導(dǎo)航菜單.

www.domain.com/store/home.php

www.domain.com/store/products/ipad.php

在首頁中, 可以寫:

  1. <a href="home.php">Home</a>  
  2. <a href="products/ipad.php">Ipad</a> 

但在你的ipad.php不得不寫成:

  1. <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';"><a href="../home.php">Home</a>  
  2. <a href="ipad.php">Ipad</a></span> 

因?yàn)槟夸洸灰粯? 有這么多不同版本的導(dǎo)航菜單要維護(hù), 很糟糕啊. 

因此, 請使用base標(biāo)簽.

  1. <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';"><head>  
  2. <base href="http://www.domain.com/store/">  
  3. </head>  
  4. <body>  
  5. <a href="home.php">Home</a>  
  6. <a href="products/ipad.php">Ipad</a>  
  7. </body>  
  8. </html></span> 

現(xiàn)在, 這段代碼放在應(yīng)用的各個目錄文件中行為都一致. 

31. 永遠(yuǎn)不要將 error_reporting 設(shè)為 0

關(guān)閉不相的錯誤報(bào)告. E_FATAL 錯誤是很重要的. 

  1. <span style="color:#333333;font-family:'Helvetica, Arial, sans-serif';">ini_set('display_errors', 1);  
  2. error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);</span> 

32. 注意平臺體系結(jié)構(gòu)

integer在32位和64位體系結(jié)構(gòu)中長度是不同的. 因此某些函數(shù)如 strtotime 的行為會不同.

在64位的機(jī)器中, 你會看到如下的輸出.

  1. <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">$ php -a  
  2. Interactive shell  
  3.  
  4. php > echo strtotime("0000-00-00 00:00:00");  
  5. -62170005200  
  6. php > echo strtotime('1000-01-30');  
  7. -30607739600  
  8. php > echo strtotime('2100-01-30');  
  9. 4104930600</span> 

但在32位機(jī)器中, 它們將是bool(false). 查看這里, 了解更多.

33. 不要過分依賴 set_time_limit

如果你想限制最小時(shí)間, 可以使用下面的腳本:

  1. <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">set_time_limit(30);  
  2.  
  3. //Rest of the code</span> 

高枕無憂嗎?  注意任何外部的執(zhí)行, 如系統(tǒng)調(diào)用,socket操作, 數(shù)據(jù)庫操作等, 就不在set_time_limits的控制之下.

 因此, 就算數(shù)據(jù)庫花費(fèi)了很多時(shí)間查詢, 腳本也不會停止執(zhí)行. 視情況而定.

34. 使用擴(kuò)展庫

一些例子:

>>mPDF -- 能通過html生成pdf文檔

>>PHPExcel -- 讀寫excel

>>PhpMailer -- 輕松處理發(fā)送包含附近的郵件

>>pChart -- 使用php生成報(bào)表

使用開源庫完成復(fù)雜任務(wù), 如生成pdf, ms-excel文件, 報(bào)表等.

35. 使用MVC框架

是時(shí)候使用像 codeigniter 這樣的MVC框架了. MVC框架并不強(qiáng)迫你寫面向?qū)ο蟮拇a. 它們僅將php代碼與html分離.

>>明確區(qū)分php和html代碼. 在團(tuán)隊(duì)協(xié)作中有好處, 設(shè)計(jì)師和程序員可以同時(shí)工作.

>>面向?qū)ο笤O(shè)計(jì)的函數(shù)能讓你更容易維護(hù)

>>內(nèi)建函數(shù)完成了很多工作, 你不需要重復(fù)編寫

>>開發(fā)大的應(yīng)用是必須的

>>很多建議, 技巧和hack已被框架實(shí)現(xiàn)了

36. 時(shí)??纯?phpbench 

phpbench 提供了些php基本操作的基準(zhǔn)測試結(jié)果, 它展示了一些徽小的語法變化是怎樣導(dǎo)致巨大差異的.

查看php站點(diǎn)的評論, 有問題到IRC提問, 時(shí)常閱讀開源代碼, 使用Linux開發(fā). 

英文:http://www.binarytides.com/blog/35-techniques-to-enhance-your-php-code/

原文鏈接:http://www.oschina.net/question/1579_47231

【編輯推薦】

  1. PHP源碼已遷移至GitHub
  2. 使用 PHP 直接在共享內(nèi)存中存儲數(shù)據(jù)集
  3. 十個超級有用的PHP代碼片段
  4. PHP 5.3.9正式版發(fā)布!
  5. 2011年最熱門的開源PHP項(xiàng)目回顧
責(zé)任編輯:林師授 來源: OSCHINA
相關(guān)推薦

2023-01-06 18:31:46

準(zhǔn)確命名

2016-02-23 11:03:03

代碼質(zhì)量編寫函數(shù)

2009-06-03 15:31:40

Eclipse插件提高代碼質(zhì)量

2016-02-24 16:03:34

代碼質(zhì)量編寫函數(shù)

2022-08-04 09:01:45

TypeScriptMicrosoft

2012-11-07 09:48:26

2015-08-11 09:39:25

重構(gòu)提高代碼質(zhì)量

2012-07-30 13:15:18

代碼

2015-07-15 10:27:48

Android代碼質(zhì)量工具

2010-05-20 09:07:30

jQuery

2024-02-19 14:50:42

編碼原則軟件開發(fā)

2017-08-18 13:02:15

大數(shù)據(jù)數(shù)據(jù)質(zhì)量

2015-05-06 09:20:34

代碼質(zhì)量代碼審查實(shí)踐

2011-07-10 00:29:18

PHP

2024-01-05 18:01:17

高并發(fā)策略程序

2023-03-16 08:01:56

TypeScript開源編程語言

2012-11-02 14:37:58

代碼編程語言

2020-02-26 12:03:36

代碼漏洞產(chǎn)品質(zhì)量

2023-05-29 09:21:53

SQLAlchemySQL

2024-05-24 09:57:34

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號