成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

提高PHP代碼質量36計

開發 后端
本文詳細的介紹了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.  
  4. 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.  
  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. 使用可跨平臺的函數執行命令

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

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

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

上面的函數將運行shell命令, 只要有一個系統函數可用, 這保持了代碼的一致性. 

5. 靈活編寫函數

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

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

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

現在, 同個函數可以處理不同類型的輸入參數了. 可以參照上面的例子重構你的多處代碼, 使其更智能.

6. 有意忽略php關閉標簽

我很想知道為什么這么多關于php建議的博客文章都沒提到這點.

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

這將節約你很多時間. 我們舉個例子:

一個 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. 為什么? 因為 “super extra character” 已經被輸出了. 現在你得開始調試啦. 這會花費大量時間尋找 super extra 的位置.

因此, 養成省略關閉符的習慣:

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

這會更好. 

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

這稱為輸出緩沖, 假如說你已在不同的函數輸出內容:

  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(); 
替代方案, 在某地方集中收集輸出. 你可以存儲在函數的局部變量中, 也可以使用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(); 

為什么需要輸出緩沖:

>>可以在發送給瀏覽器前更改輸出. 如 str_replaces 函數或可能是 preg_replaces 或添加些監控/調試的html內容.

>>輸出給瀏覽器的同時又做php的處理很糟糕. 你應該看到過有些站點的側邊欄或中間出現錯誤信息. 知道為什么會發生嗎? 因為處理和輸出混合了.

8. 發送正確的mime類型頭信息, 如果輸出非html內容的話.

輸出一些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

工作得不錯. 但需要一些改進.

  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行. 該行告知瀏覽器發送的是xml類型的內容. 所以瀏覽器能正確的處理. 很多的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連接設置正確的字符編碼

曾經遇到過在mysql表中設置了unicode/utf-8編碼,  phpadmin也能正確顯示, 但當你獲取內容并在頁面輸出的時候,會出現亂碼. 這里的問題出在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');  

一旦連接數據庫, ***設置連接的 characterset. 你的應用如果要支持多語言, 這么做是必須的.

10. 使用 htmlentities 設置正確的編碼選項

php5.4前, 字符的默認編碼是ISO-8859-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. $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"] 

優雅乎?

13. 寫文件前, 檢查目錄寫權限

寫或保存文件前, 確保目錄是可寫的, 假如不可寫, 輸出錯誤信息. 這會節約你很多調試時間. linux系統中, 需要處理權限, 目錄權限不當會導致很多很多的問題, 文件也有可能無法讀取等等.

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

  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. 更改應用創建的文件權限

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

  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  

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

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

現在你從submit按鈕值中解脫出來了.

16. 為函數內總具有相同值的變量定義成靜態變量

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

用靜態變量取代:

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

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

從現在開始, 使用應用相關的key和一個包裝函數:

  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. 將工具函數封裝到類中

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

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

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

  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內建有同名的函數, 這樣可以避免沖突.

另一種看法是, 你可以在同個應用中為同個類維護多個版本, 而不導致沖突. 這是封裝的基本好處, 無它.

19. Bunch of silly tips 

>>使用echo取代print

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

>>不要使用 short tag

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

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

>>不要在循環中調用函數

>>isset比strlen快

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

>>不要刪除循環或者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快速處理數組

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

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

但使用 array_map 更簡單:

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

這會為$arr數組的每個元素都申請調用trim. 另一個類似的函數是 array_walk. 請查閱文檔學習更多技巧.

21. 使用 php filter 驗證數據

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

php的filter擴展提供了簡單的方式驗證和檢查輸入.

22. 強制類型檢查

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

這是個好習慣.

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

如果你使用php開發大型的應用, php承擔了很多運算量, 速度會是一個很重要的指標. 使用profile幫助優化代碼. 可使用

xdebug和webgrid.

24. 小心處理大數組

對于大的數組和字符串, 必須小心處理. 常見錯誤是發生數組拷貝導致內存溢出,拋出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 ? 

 

當導入或導出csv文件時, 常常會這么做.

不要認為上面的代碼會經常因內存限制導致腳本崩潰. 對于小的變量是沒問題的, 但處理大數組的時候就必須避免.

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

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

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

  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 它們, 讓內存得以釋放,減輕腳本負擔.

25.  由始至終使用單一數據庫連接

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

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

使用多個連接是個糟糕的, 它們會拖慢應用, 因為創建連接需要時間和占用內存.

特定情況使用單例模式, 如數據庫連接.

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> 

這不是個建壯的方案. 它有些缺點:

>>每次都手動轉義值

>>驗證查詢是否正確

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

>>很難維護復雜的查詢

因此使用函數封裝:

  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> 

看到了嗎? 這樣會更易讀和擴展. record_data 函數小心的處理了轉義. 

***的優點是數據被預處理為一個數組, 任何語法錯誤都會被捕獲.

該函數應該定義在某個database類中, 你可以像 $db->insert_record這樣調用.

查看本文, 看看怎樣讓你處理數據庫更容易.

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

27. 將數據庫生成的內容緩存到靜態文件中

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

好處:

>>節約php處理頁面的時間, 執行更快

>>更少的數據庫查詢意味著更少的mysql連接開銷

28. 在數據庫中保存sessio-

base 標簽非常有用. 假設你的應用分成幾個子目錄, 它們都要包括相同的導航菜單.

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> 

因為目錄不一樣. 有這么多不同版本的導航菜單要維護, 很糟糕啊. 

因此, 請使用base標簽.

  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> 

現在, 這段代碼放在應用的各個目錄文件中行為都一致. 

31. 永遠不要將 error_reporting 設為 0

關閉不相的錯誤報告. 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. 注意平臺體系結構

integer在32位和64位體系結構中長度是不同的. 因此某些函數如 strtotime 的行為會不同.

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

  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位機器中, 它們將是bool(false). 查看這里, 了解更多.

33. 不要過分依賴 set_time_limit

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

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

高枕無憂嗎?  注意任何外部的執行, 如系統調用,socket操作, 數據庫操作等, 就不在set_time_limits的控制之下.

 因此, 就算數據庫花費了很多時間查詢, 腳本也不會停止執行. 視情況而定.

34. 使用擴展庫

一些例子:

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

>>PHPExcel -- 讀寫excel

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

>>pChart -- 使用php生成報表

使用開源庫完成復雜任務, 如生成pdf, ms-excel文件, 報表等.

35. 使用MVC框架

是時候使用像 codeigniter 這樣的MVC框架了. MVC框架并不強迫你寫面向對象的代碼. 它們僅將php代碼與html分離.

>>明確區分php和html代碼. 在團隊協作中有好處, 設計師和程序員可以同時工作.

>>面向對象設計的函數能讓你更容易維護

>>內建函數完成了很多工作, 你不需要重復編寫

>>開發大的應用是必須的

>>很多建議, 技巧和hack已被框架實現了

36. 時常看看 phpbench 

phpbench 提供了些php基本操作的基準測試結果, 它展示了一些徽小的語法變化是怎樣導致巨大差異的.

查看php站點的評論, 有問題到IRC提問, 時常閱讀開源代碼, 使用Linux開發. 

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

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

【編輯推薦】

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

2016-02-24 16:03:34

代碼質量編寫函數

2022-08-04 09:01:45

TypeScriptMicrosoft

2016-02-23 11:03:03

代碼質量編寫函數

2023-01-06 18:31:46

準確命名

2009-06-03 15:31:40

Eclipse插件提高代碼質量

2012-11-07 09:48:26

2015-08-11 09:39:25

重構提高代碼質量

2012-07-30 13:15:18

代碼

2015-07-15 10:27:48

Android代碼質量工具

2017-08-18 13:02:15

大數據數據質量

2010-05-20 09:07:30

jQuery

2024-02-19 14:50:42

編碼原則軟件開發

2015-05-06 09:20:34

代碼質量代碼審查實踐

2023-03-16 08:01:56

TypeScript開源編程語言

2024-01-05 18:01:17

高并發策略程序

2012-11-02 14:37:58

代碼編程語言

2011-07-10 00:29:18

PHP

2020-02-26 12:03:36

代碼漏洞產品質量

2024-05-24 09:57:34

2023-05-29 09:21:53

SQLAlchemySQL
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 99久久成人| 久热免费在线 | 久久一区二区视频 | 色姑娘综合网 | 在线观看黄免费 | 久久久av中文字幕 | 青久草视频 | 亚洲国产偷| 浴室洗澡偷拍一区二区 | 国产精品69毛片高清亚洲 | 伊人一二三 | 久久久久亚洲精品 | 欧美激情一区二区三区 | 久久国产精品72免费观看 | 亚洲日韩中文字幕一区 | 亚洲视频观看 | 99久久精品国产毛片 | 国产成人综合在线 | 日韩中文字幕区 | 国产亚洲欧美在线视频 | 免费污视频 | 狠狠av| 草樱av| 欧美 中文字幕 | 久久黄网 | 日韩欧美精品在线 | 国产在线对白 | 亚洲精品9999 | 久久成人国产精品 | 日本一区二区在线视频 | 欧美日本一区 | 久草网站 | 国产精品久久久久久久7电影 | 成人不卡视频 | 亚洲视频在线看 | 亚洲精品乱码久久久久久按摩观 | 久久久久精 | 人人色视频 | 一级片在线观看 | 欧美日韩高清在线一区 | 亚洲福利视频一区二区 |