日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
提高PHP代碼質(zhì)量36計(jì)

1.不要使用相對(duì)路徑

創(chuàng)新互聯(lián)-專(zhuān)業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比魚(yú)臺(tái)網(wǎng)站開(kāi)發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫(kù),直接使用。一站式魚(yú)臺(tái)網(wǎng)站制作公司更省心,省錢(qián),快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋魚(yú)臺(tái)地區(qū)。費(fèi)用合理售后完善,十余年實(shí)體公司更值得信賴。

常常會(huì)看到: 

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

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

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

因此會(huì)檢查過(guò)多路徑.

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

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

因此***選擇是使用絕對(duì)路徑:

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

我們定義了一個(gè)絕對(duì)路徑, 值被寫(xiě)死了. 我們還可以改進(jìn)它. 路徑 /var/www/project 也可能會(huì)改變, 那么我們每次都要改變它嗎? 不是的, 我們可以使用__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ú)論你移到哪個(gè)目錄, 如移到一個(gè)外網(wǎng)的服務(wù)器上, 代碼無(wú)須更改便可正確運(yùn)行.

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

可以在腳本頭部引入多個(gè)文件, 像類(lèi)庫(kù), 工具文件和助手函數(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)編寫(xiě)個(gè)助手函數(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'); 

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

將來(lái)你可以按需擴(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.     }  

還可做得更多:

為同樣文件查找多個(gè)目錄

能很容易的改變放置類(lèi)文件的目錄, 無(wú)須在代碼各處一一修改

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

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

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

在開(kāi)發(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. 使用可跨平臺(tái)的函數(shù)執(zhí)行命令

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

更好的方案是封成函數(shù)一個(gè)可跨平臺(tái)的函數(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命令, 只要有一個(gè)系統(tǒng)函數(shù)可用, 這保持了代碼的一致性. 

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

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

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

 
 
 
  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)在, 同個(gè)函數(shù)可以處理不同類(lèi)型的輸入?yún)?shù)了. 可以參照上面的例子重構(gòu)你的多處代碼, 使其更智能.

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

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

 
 
 
  1.  
  2. echo "Hello";  
  3.  
  4. //Now dont close this tag 

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

一個(gè) super_class.php 文件

 
 
 
  1. class super_class  
  2. {  
  3.     function super_function()  
  4.     {  
  5.         //super code  
  6.     }  
  7. }  
  8. ?>  
  9. //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 

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

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

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

這會(huì)更好. 

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

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

    
 
 
  1. function print_header()  
  2. {  
  3.     echo "Site Log and Login links
";  
  • }  
  •  
  • function print_footer()  
  • {  
  •     echo "Site was made by me
  • ";  
  • }  
  •  
  • print_header();  
  • for($i = 0 ; $i < 100; $i++)  
  • {  
  •     echo "I is : $i ';  
  • }  
  • print_footer(); 
  • 替代方案, 在某地方集中收集輸出. 你可以存儲(chǔ)在函數(shù)的局部變量中, 也可以使用ob_start和ob_end_clean. 如下:

        
     
     
    1. function print_header()  
    2. {  
    3.     $o = "Site Log and Login links
    ";  
  •     return $o;  
  • }  
  •  
  • function print_footer()  
  • {  
  •     $o = "Site was made by me
  • ";  
  •     return $o;  
  • }  
  •  
  • echo print_header();  
  • for($i = 0 ; $i < 100; $i++)  
  • {  
  •     echo "I is : $i ';  
  • }  
  • echo print_footer(); 
  • 為什么需要輸出緩沖:

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

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

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

    輸出一些xml.

     
     
     
    1. $xml = '';  
    2. $xml = "  
    3.   0  
    4. ";  
    5.  
    6. //Send xml data  
    7. echo $xml; 

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

     
     
     
    1. $xml = '';  
    2. $xml = "  
    3.   0  
    4. ";  
    5.  
    6. //Send xml data  
    7. header("content-type: text/xml");  
    8. echo $xml; 

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

    類(lèi)似的有 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)遇到過(guò)在mysql表中設(shè)置了unicode/utf-8編碼,  phpadmin也能正確顯示, 但當(dāng)你獲取內(nèi)容并在頁(yè)面輸出的時(shí)候,會(huì)出現(xiàn)亂碼. 這里的問(wè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)   
    6. {  
    7.     die ("Could not connect to the database host: ". 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ù)庫(kù), ***設(shè)置連接的 characterset. 你的應(yīng)用如果要支持多語(yǔ)言, 這么做是必須的.

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

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

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

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

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

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

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

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

    時(shí)常會(huì)用php輸出動(dòng)態(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. 寫(xiě)文件前, 檢查目錄寫(xiě)權(quán)限

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

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

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

    這大體上正確. 但有些間接的問(wèn)題. file_put_contents 可能會(huì)由于幾個(gè)原因失敗:

    >>父目錄不存在

    >>目錄存在, 但不可寫(xiě)

    >>文件被寫(xiě)鎖住?

    所以寫(xiě)文件前做明確的檢查更好.

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

    這么做后, 你會(huì)得到一個(gè)文件在何處寫(xiě)及為什么失敗的明確信息.

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

    在 linux環(huán)境中, 權(quán)限問(wèn)題可能會(huì)浪費(fèi)你很多時(shí)間. 從今往后, 無(wú)論何時(shí), 當(dāng)你創(chuàng)建一些文件后, 確保使用chmod設(shè)置正確權(quán)限. 否則的話, 可能文件先是由"php"用戶創(chuàng)建, 但你用其它的用戶登錄工作, 系統(tǒng)將會(huì)拒絕訪問(wèn)或打開(kāi)文件, 你不得不奮力獲取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按鈕值來(lái)檢查表單提交行為

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

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

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

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

    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 "Delaying for $sync_delay seconds...";  
    7.     sleep($sync_delay);  
    8.     echo "Done ";  

    用靜態(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 "Delaying for $sync_delay seconds...";  
    12.     sleep($sync_delay);  
    13.     echo "Done ";  

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

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

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

    從現(xiàn)在開(kāi)始, 使用應(yīng)用相關(guān)的key和一個(gè)包裝函數(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ù)封裝到類(lèi)中

    假如你在某文件中定義了很多工具函數(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)用各處. 你可能想將他們封裝到某個(gè)類(lèi)中:

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

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

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

    19. Bunch of silly tips 

    >>使用echo取代print

    >>使用str_replace取代preg_replace, 除非你絕對(duì)需要

    >>不要使用 short tag

    >>簡(jiǎn)單字符串用單引號(hào)取代雙引號(hào)

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

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

    >>isset比strlen快

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

    >>不要?jiǎng)h除循環(huán)或者if-else的括號(hào)

    不要這樣寫(xiě)代碼:

     
     
     
    1. if($a == true) $a_count++; 

    這絕對(duì)WASTE.

    寫(xiě)成:

     
     
     
    1. if($a == true)  
    2. {  
    3.     $a_count++;  

    不要嘗試省略一些語(yǔ)法來(lái)縮短代碼. 而是讓你的邏輯簡(jiǎn)短.

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

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

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

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

    但使用 array_map 更簡(jiǎn)單:

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

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

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

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

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

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

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

    這是個(gè)好習(xí)慣.

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

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

    xdebug和webgrid.

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

    對(duì)于大的數(shù)組和字符串, 必須小心處理. 常見(jiàn)錯(cuò)誤是發(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í), 常常會(huì)這么做.

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

    確保通過(guò)引用傳遞, 或存儲(chǔ)在類(lèi)變量中:

     
     
     
    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ù)庫(kù)連接

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

     
     
     
    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 .....");  

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

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

    26. 避免直接寫(xiě)SQL, 抽象之

    不厭其煩的寫(xiě)了太多如下的語(yǔ)句:

     
     
     
    1. $query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";  
    2. $db->query($query); //call to mysqli_query() 

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

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

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

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

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

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

     
     
     
    1. 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); 

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

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

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

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

    類(lèi)似的也可以編寫(xiě)update,select,delete方法. 試試吧.

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

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

    好處:

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

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

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

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

    www.domain.com/store/home.php

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

    在首頁(yè)中, 可以寫(xiě):

     
     
     
    1. Home  
    2. Ipad 

    但在你的ipad.php不得不寫(xiě)成:

     
     
     
    1. Home  
    2. Ipad 

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

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

     
     
     
    1.  
    2.  
    3.  
    4.  
    5. Home  
    6. Ipad  
    7.  
    8.  

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

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

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

     
     
     
    1. ini_set('display_errors', 1);  
    2. error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); 

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

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

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

     
     
     
    1. $ 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 

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

    33. 不要過(guò)分依賴 set_time_limit

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

     
     
     
    1. set_time_limit(30);  
    2.  
    3. //Rest of the code 

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

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

    34. 使用擴(kuò)展庫(kù)

    一些例子:

    >>mPDF -- 能通過(guò)html生成pdf文檔

    >>PHPExcel -- 讀寫(xiě)excel

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

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

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

    35. 使用MVC框架

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

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

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

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

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

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

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

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

    查看php站點(diǎn)的評(píng)論, 有問(wèn)題到IRC提問(wèn), 時(shí)常閱讀開(kāi)源代碼, 使用Linux開(kāi)發(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)存中存儲(chǔ)數(shù)據(jù)集
    3. 十個(gè)超級(jí)有用的PHP代碼片段
    4. PHP 5.3.9正式版發(fā)布!
    5. 2011年最熱門(mén)的開(kāi)源PHP項(xiàng)目回顧

    當(dāng)前標(biāo)題:提高PHP代碼質(zhì)量36計(jì)
    轉(zhuǎn)載注明:http://www.5511xx.com/article/ccidgdd.html