提高PHP代碼質(zhì)量36計(jì)
1.不要使用相對路徑
常常會看到:
- require_once('../../lib/some_class.php');
該方法有很多缺點(diǎn):
它首先查找指定的php包含路徑, 然后查找當(dāng)前目錄.
因此會檢查過多路徑.
如果該腳本被另一目錄的腳本包含, 它的基本目錄變成了另一腳本所在的目錄.
另一問題, 當(dāng)定時(shí)任務(wù)運(yùn)行該腳本, 它的上級目錄可能就不是工作目錄了.
因此***選擇是使用絕對路徑:
- define('ROOT' , '/var/www/project/');
- require_once(ROOT . '../../lib/some_class.php');
- //rest of the code
我們定義了一個絕對路徑, 值被寫死了. 我們還可以改進(jìn)它. 路徑 /var/www/project 也可能會改變, 那么我們每次都要改變它嗎? 不是的, 我們可以使用__FILE__常量, 如:
- //suppose your script is /var/www/project/index.php
- //Then __FILE__ will always have that full path.
- define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
- require_once(ROOT . '../../lib/some_class.php');
- //rest of the code
現(xiàn)在, 無論你移到哪個目錄, 如移到一個外網(wǎng)的服務(wù)器上, 代碼無須更改便可正確運(yùn)行.
2. 不要直接使用 require, include, include_once, required_once
可以在腳本頭部引入多個文件, 像類庫, 工具文件和助手函數(shù)等, 如:
- require_once('lib/Database.php');
- require_once('lib/Mail.php');
- require_once('helpers/utitlity_functions.php');
這種用法相當(dāng)原始. 應(yīng)該更靈活點(diǎn). 應(yīng)編寫個助手函數(shù)包含文件. 例如:
- function load_class($class_name)
- {
- //path to the class file
- $path = ROOT . '/lib/' . $class_name . '.php');
- require_once( $path );
- }
- load_class('Database');
- load_class('Mail');
有什么不一樣嗎? 該代碼更具可讀性.
將來你可以按需擴(kuò)展該函數(shù), 如:
- function load_class($class_name)
- {
- //path to the class file
- $path = ROOT . '/lib/' . $class_name . '.php');
- if(file_exists($path))
- {
- require_once( $path );
- }
- }
還可做得更多:
為同樣文件查找多個目錄
能很容易的改變放置類文件的目錄, 無須在代碼各處一一修改
可使用類似的函數(shù)加載文件, 如html內(nèi)容.
3. 為應(yīng)用保留調(diào)試代碼
在開發(fā)環(huán)境中, 我們打印數(shù)據(jù)庫查詢語句, 轉(zhuǎn)存有問題的變量值, 而一旦問題解決, 我們注釋或刪除它們. 然而更好的做法是保留調(diào)試代碼.
在開發(fā)環(huán)境中, 你可以:
- define('ENVIRONMENT' , 'development');
- if(! $db->query( $query )
- {
- if(ENVIRONMENT == 'development')
- {
- echo "$query failed";
- }
- else
- {
- echo "Database error. Please contact administrator";
- }
- }
在服務(wù)器中, 你可以:
- define('ENVIRONMENT' , 'production');
- if(! $db->query( $query )
- {
- if(ENVIRONMENT == 'development')
- {
- echo "$query failed";
- }
- else
- {
- echo "Database error. Please contact administrator";
- }
- }
4. 使用可跨平臺的函數(shù)執(zhí)行命令
system, exec, passthru, shell_exec 這4個函數(shù)可用于執(zhí)行系統(tǒng)命令. 每個的行為都有細(xì)微差別. 問題在于, 當(dāng)在共享主機(jī)中, 某些函數(shù)可能被選擇性的禁用. 大多數(shù)新手趨于每次首先檢查哪個函數(shù)可用, 然而再使用它.
更好的方案是封成函數(shù)一個可跨平臺的函數(shù).
- /**
- 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');
上面的函數(shù)將運(yùn)行shell命令, 只要有一個系統(tǒng)函數(shù)可用, 這保持了代碼的一致性.
5. 靈活編寫函數(shù)
- function add_to_cart($item_id , $qty)
- {
- $_SESSION['cart']['item_id'] = $qty;
- }
- add_to_cart( 'IPHONE3' , 2 );
使用上面的函數(shù)添加單個項(xiàng)目. 而當(dāng)添加項(xiàng)列表的時(shí)候,你要創(chuàng)建另一個函數(shù)嗎? 不用, 只要稍加留意不同類型的參數(shù), 就會更靈活. 如:
- 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) );
現(xiàn)在, 同個函數(shù)可以處理不同類型的輸入?yún)?shù)了. 可以參照上面的例子重構(gòu)你的多處代碼, 使其更智能.
6. 有意忽略php關(guān)閉標(biāo)簽
我很想知道為什么這么多關(guān)于php建議的博客文章都沒提到這點(diǎn).
- <?php
- echo "Hello";
- //Now dont close this tag
這將節(jié)約你很多時(shí)間. 我們舉個例子:
一個 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. 為什么? 因?yàn)?nbsp;“super extra character” 已經(jīng)被輸出了. 現(xiàn)在你得開始調(diào)試?yán)? 這會花費(fèi)大量時(shí)間尋找 super extra 的位置.
因此, 養(yǎng)成省略關(guān)閉符的習(xí)慣:
- <?php
- class super_class
- {
- function super_function()
- {
- //super code
- }
- }
- //No closing tag
這會更好.
7. 在某地方收集所有輸入, 一次輸出給瀏覽器
這稱為輸出緩沖, 假如說你已在不同的函數(shù)輸出內(nèi)容:
替代方案, 在某地方集中收集輸出. 你可以存儲在函數(shù)的局部變量中, 也可以使用ob_start和ob_end_clean. 如下:
- 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();
- 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();
為什么需要輸出緩沖:
>>可以在發(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.
- $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';
- $xml = "<response>
- <code>0</code>
- </response>";
- //Send xml data
- echo $xml;
工作得不錯. 但需要一些改進(jìn).
- $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行. 該行告知瀏覽器發(fā)送的是xml類型的內(nèi)容. 所以瀏覽器能正確的處理. 很多的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連接設(shè)置正確的字符編碼
曾經(jīng)遇到過在mysql表中設(shè)置了unicode/utf-8編碼, phpadmin也能正確顯示, 但當(dāng)你獲取內(nèi)容并在頁面輸出的時(shí)候,會出現(xiàn)亂碼. 這里的問題出在mysql連接的字符編碼.
- //Attempt to connect to database
- $c = mysqli_connect($this->host , $this->username, $this->password);
- //Check connection validity
- if (!$c)
- {
- 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');
- }
一旦連接數(shù)據(jù)庫, ***設(shè)置連接的 characterset. 你的應(yīng)用如果要支持多語言, 這么做是必須的.
10. 使用 htmlentities 設(shè)置正確的編碼選項(xiàng)
php5.4前, 字符的默認(rèn)編碼是ISO-8859-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)容:
- $images = array(
- 'myself.png' , 'friends.png' , 'colleagues.png'
- );
- $js_code = '';
- foreach($images as $image)
- {
- $js_code .= "'$image' ,";
- }
- $js_code = 'var images = [' . $js_code . ']; ';
- echo $js_code;
- //Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,];
更聰明的做法, 使用 json_encode:
- $images = array(
- 'myself.png' , 'friends.png' , 'colleagues.png'
- );
- $js_code = 'var images = ' . json_encode($images);
- echo $js_code;
- //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)用足夠智能, 輸出某些重要信息.
- $contents = "All the content";
- $file_path = "/var/www/project/content.txt";
- file_put_contents($file_path , $contents);
這大體上正確. 但有些間接的問題. file_put_contents 可能會由于幾個原因失敗:
>>父目錄不存在
>>目錄存在, 但不可寫
>>文件被寫鎖住?
所以寫文件前做明確的檢查更好.
- $contents = "All the content";
- $dir = '/var/www/project';
- $file_path = $dir . "/content.txt";
- if(is_writable($dir))
- {
- file_put_contents($file_path , $contents);
- }
- else
- {
- 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)限等等.
- // Read and write for owner, read for everybody else
- chmod("/somedir/somefile", 0644);
- // Everything for owner, read and execute for others
- chmod("/somedir/somefile", 0755);
15. 不要依賴submit按鈕值來檢查表單提交行為
- if($_POST['submit'] == 'Save')
- {
- //Save the things
- }
上面大多數(shù)情況正確, 除了應(yīng)用是多語言的. 'Save' 可能代表其它含義. 你怎么區(qū)分它們呢. 因此, 不要依賴于submit按鈕的值.
- if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) )
- {
- //Save the things
- }
現(xiàn)在你從submit按鈕值中解脫出來了.
16. 為函數(shù)內(nèi)總具有相同值的變量定義成靜態(tài)變量
- //Delay for some time
- function delay()
- {
- $sync_delay = get_option('sync_delay');
- echo "<br />Delaying for $sync_delay seconds...";
- sleep($sync_delay);
- echo "Done <br />";
- }
用靜態(tài)變量取代:
- //Delay for some time
- function delay()
- {
- static $sync_delay = null;
- if($sync_delay == null)
- {
- $sync_delay = get_option('sync_delay');
- }
- echo "<br />Delaying for $sync_delay seconds...";
- sleep($sync_delay);
- echo "Done <br />";
- }
17. 不要直接使用 $_SESSION 變量
- $_SESSION['username'] = $username;
- $username = $_SESSION['username'];
這會導(dǎo)致某些問題. 如果在同個域名中運(yùn)行了多個應(yīng)用, session 變量可能會沖突. 兩個不同的應(yīng)用可能使用同一個session key. 例如, 一個前端門戶, 和一個后臺管理系統(tǒng)使用同一域名.
從現(xiàn)在開始, 使用應(yīng)用相關(guān)的key和一個包裝函數(shù):
- define('APP_ID' , 'abc_corp_ecommerce');
- //Function to get a session variable
- function session_get($key)
- {
- $k = APP_ID . '.' . $key;
- if(isset($_SESSION[$k]))
- {
- return $_SESSION[$k];
- }
- return false;
- }
- //Function set the session variable
- function session_set($key , $value)
- {
- $k = APP_ID . '.' . $key;
- $_SESSION[$k] = $value;
- return true;
- }
18. 將工具函數(shù)封裝到類中
假如你在某文件中定義了很多工具函數(shù):
- function utility_a()
- {
- //This function does a utility thing like string processing
- }
- function utility_b()
- {
- //This function does nother utility thing like database processing
- }
- function utility_c()
- {
- //This function is ...
- }
這些函數(shù)的使用分散到應(yīng)用各處. 你可能想將他們封裝到某個類中:
- class Utility
- {
- public static function utility_a()
- {
- }
- public static function utility_b()
- {
- }
- public static function utility_c()
- {
- }
- }
- //and call them as
- $a = Utility::utility_a();
- $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的括號
不要這樣寫代碼:
- <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">if($a == true) $a_count++;</span>
這絕對WASTE.
寫成:
- <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">if($a == true)
- {
- $a_count++;
- }</span>
不要嘗試省略一些語法來縮短代碼. 而是讓你的邏輯簡短.
>>使用有高亮語法顯示的文本編輯器. 高亮語法能讓你減少錯誤.
20. 使用array_map快速處理數(shù)組
比如說你想 trim 數(shù)組中的所有元素. 新手可能會:
- foreach($arr as $c => $v)
- {
- $arr[$c] = trim($v);
- }
但使用 array_map 更簡單:
- $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)制類型檢查
- $amount = intval( $_GET['amount'] );
- $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
- $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
- $cc = $db_records_in_array_format; //2MB more
- some_function($cc); //Another 2MB ?
當(dāng)導(dǎo)入或?qū)С鯿sv文件時(shí), 常常會這么做.
不要認(rèn)為上面的代碼會經(jīng)常因內(nèi)存限制導(dǎo)致腳本崩潰. 對于小的變量是沒問題的, 但處理大數(shù)組的時(shí)候就必須避免.
確保通過引用傳遞, 或存儲在類變量中:
- $a = get_large_array();
- pass_to_function(&$a);
這么做后,向函數(shù)傳遞變量引用(而不是拷貝數(shù)組). 查看文檔.
- class A
- {
- function first()
- {
- $this->a = get_large_array();
- $this->pass_to_function();
- }
- function pass_to_function()
- {
- //process $this->a
- }
- }
盡快的 unset 它們, 讓內(nèi)存得以釋放,減輕腳本負(fù)擔(dān).
25. 由始至終使用單一數(shù)據(jù)庫連接
確保你的腳本由始至終都使用單一的數(shù)據(jù)庫連接. 在開始處正確的打開連接, 使用它直到結(jié)束, ***關(guān)閉它. 不要像下面這樣在函數(shù)中打開連接:
- function add_to_cart()
- {
- $db = new Database();
- $db->query("INSERT INTO cart .....");
- }
- function empty_cart()
- {
- $db = new Database();
- $db->query("DELETE FROM cart .....");
- }
使用多個連接是個糟糕的, 它們會拖慢應(yīng)用, 因?yàn)閯?chuàng)建連接需要時(shí)間和占用內(nèi)存.
特定情況使用單例模式, 如數(shù)據(jù)庫連接.
26. 避免直接寫SQL, 抽象之
不厭其煩的寫了太多如下的語句:
- <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">$query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')";
- $db->query($query); //call to mysqli_query()</span>
這不是個建壯的方案. 它有些缺點(diǎn):
>>每次都手動轉(zhuǎn)義值
>>驗(yàn)證查詢是否正確
>>查詢的錯誤會花很長時(shí)間識別(除非每次都用if-else檢查)
>>很難維護(hù)復(fù)雜的查詢
因此使用函數(shù)封裝:
- <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">function insert_record($table_name , $data)
- {
- foreach($data as $key => $value)
- {
- //mysqli_real_escape_string
- $data[$key] = $db->mres($value);
- }
- $fields = implode(',' , array_keys($data));
- $values = "'" . implode("','" , array_values($data)) . "'";
- //Final query
- $query = "INSERT INTO {$table}($fields) VALUES($values)";
- return $db->query($query);
- }
- $data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone);
- 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
在首頁中, 可以寫:
- <a href="home.php">Home</a>
- <a href="products/ipad.php">Ipad</a>
但在你的ipad.php不得不寫成:
- <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';"><a href="../home.php">Home</a>
- <a href="ipad.php">Ipad</a></span>
因?yàn)槟夸洸灰粯? 有這么多不同版本的導(dǎo)航菜單要維護(hù), 很糟糕啊.
因此, 請使用base標(biāo)簽.
- <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';"><head>
- <base href="http://www.domain.com/store/">
- </head>
- <body>
- <a href="home.php">Home</a>
- <a href="products/ipad.php">Ipad</a>
- </body>
- </html></span>
現(xiàn)在, 這段代碼放在應(yīng)用的各個目錄文件中行為都一致.
31. 永遠(yuǎn)不要將 error_reporting 設(shè)為 0
關(guān)閉不相的錯誤報(bào)告. E_FATAL 錯誤是很重要的.
- <span style="color:#333333;font-family:'Helvetica, Arial, sans-serif';">ini_set('display_errors', 1);
- error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT);</span>
32. 注意平臺體系結(jié)構(gòu)
integer在32位和64位體系結(jié)構(gòu)中長度是不同的. 因此某些函數(shù)如 strtotime 的行為會不同.
在64位的機(jī)器中, 你會看到如下的輸出.
- <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">$ php -a
- Interactive shell
- php > echo strtotime("0000-00-00 00:00:00");
- -62170005200
- php > echo strtotime('1000-01-30');
- -30607739600
- php > echo strtotime('2100-01-30');
- 4104930600</span>
但在32位機(jī)器中, 它們將是bool(false). 查看這里, 了解更多.
33. 不要過分依賴 set_time_limit
如果你想限制最小時(shí)間, 可以使用下面的腳本:
- <span style="color:#333333;font-family:''Helvetica, Arial, sans-serif'';">set_time_limit(30);
- //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
【編輯推薦】