高品質PHP代碼的50個實用技巧必備(上)_php技巧

來源:互聯網
上載者:User

50個高品質PHP代碼的實用技巧,希望大家喜歡。

1.不要使用相對路徑
常常會看到:

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

該方法有很多缺點: 它首先尋找指定的php包含路徑, 然後尋找目前的目錄。因此會檢查過多重路徑。如果該指令碼被另一目錄的指令碼包含, 它的基本目錄變成了另一指令碼所在的目錄.

另一問題, 當定時任務運行該指令碼, 它的上級目錄可能就不是工作目錄了。因此最佳選擇是使用絕對路徑:

view sourceprint? 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. define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME)); require_once(ROOT . '../../lib/some_class.php'); //rest of the code

現在, 無論你移到哪個目錄, 如移到一個外網的伺服器上, 代碼無須更改便可正確運行.

2. 不要直接使用 require, include, include_once, required_once
可以在指令碼頭部引入多個檔案, 像類庫, 工具檔案和助手函數等, 如:

require_once('lib/Database.php'); require_once('lib/Mail.php'); require_once('helpers/utitlity_functions.php');

這種用法相當原始. 應該更靈活點. 應編寫個助手函數包含檔案. 例如:

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

有什麼不一樣嗎? 該代碼更具可讀性。將來你可以按需擴充該函數, 如:

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 '; }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 '; } 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:

JavaScriptheader("content-type: application/x-javascript"); echo "var a = 10"; CSSheader("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) { die ("Could not connect to the database host: ". mysqli_connect_error()); } //Set the character set of the connectionif(!mysqli_set_charset ( $c , 'UTF8' )) { die('mysqli_set_charset() failed'); }

一旦串連資料庫, 最好設定串連的 characterset. 你的應用如果要支援多語言, 這麼做是必須的.

10. 使用 htmlentities 設定正確的編碼選項
php5.4前, 字元的預設編碼是ISO-8859-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內容:

$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"]

優雅乎?

13. 寫檔案前, 檢查目錄寫入權限
寫或儲存檔案前, 確保目錄是可寫的, 假如不可寫, 輸出錯誤資訊. 這會節約你很多調試時間. linux系統中, 需要處理許可權, 目錄許可權不當會導致很多很多的問題, 檔案也有可能無法讀取等等.
確保你的應用足夠智能, 輸出某些重要訊息.

$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. 更改應用建立的檔案許可權
在linux環境中, 許可權問題可能會浪費你很多時間. 從今往後, 無論何時, 當你建立一些檔案後, 確保使用chmod設定正確許可權. 否則的話, 可能檔案先是由”php”使用者建立, 但你用其它的使用者登入工作, 系統將會拒絕訪問或開啟檔案, 你不得不奮力擷取root許可權, 變更檔的許可權等等.

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

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

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

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

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

//Delay for some time function delay() { $sync_delay = get_option('sync_delay'); echo "Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done "; }

用靜態變數取代:

//Delay for some time function delay() { static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done "; }

17. 不要直接使用 $_SESSION 變數
某些簡單例子:

$_SESSION['username'] = $username; $username = $_SESSION['username'];

這會導致某些問題. 如果在同個網域名稱中運行了多個應用, session 變數可能會衝突. 兩個不同的應用可能使用同一個session key. 例如, 一個前端門戶, 和一個後台管理系統使用同一網域名稱。從現在開始, 使用應用相關的key和一個封裝函數:

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. 將工具函數封裝到類中
假如你在某檔案中定義了很多工具函數:

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

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

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內建有同名的函數, 這樣可以避免衝突.
另一種看法是, 你可以在同個應用中為同個類維護多個版本, 而不導致衝突. 這是封裝的基本好處, 無它.

19. Bunch of silly tips
>>使用echo取代print
>>使用str_replace取代preg_replace, 除非你絕對需要
>>不要使用 short tag
>>簡單字串用單引號取代雙引號
>>head重新導向後記得使用exit
>>不要在迴圈中調用函數
>>isset比strlen快
>>始中如一的格式化代碼
>>不要刪除迴圈或者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快速處理數組
比如說你想 trim 數組中的所有元素. 新手可能會:

foreach($arr as $c => $v) { $arr[$c] = trim($v); }

但使用 array_map 更簡單:

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

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

21. 使用 php filter 驗證資料
你肯定曾使用過Regex驗證 email , ip地址等. 是的,每個人都這麼使用. 現在, 我們想做不同的嘗試, 稱為filter.
php的filter擴充提供了簡單的方式驗證和檢查輸入.

22. 強制類型檢查

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

這是個好習慣.

23. 如果需要,使用profiler如xdebug
如果你使用php開發大型的應用, php承擔了很多運算量, 速度會是一個很重要的指標. 使用profile協助最佳化代碼. 可使用xdebug和webgrid.

24. 小心處理大數組
對於大的數組和字串, 必須小心處理. 常見錯誤是發生數組拷貝導致記憶體溢出,拋出Fatal Error of Memory size 資訊:

$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 moresome_function($cc); //Another 2MB ?

當匯入或匯出csv檔案時, 常常會這麼做。不要認為上面的代碼會經常因記憶體限制導致指令碼崩潰. 對於小的變數是沒問題的, 但處理大數組的時候就必須避免.
確保通過引用傳遞, 或儲存在類變數中:

$a = get_large_array(); pass_to_function(&$a);

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

class A { function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a } }

儘快的 unset 它們, 讓記憶體得以釋放,減輕指令碼負擔.

25. 由始至終使用單一資料庫串連
確保你的指令碼由始至終都使用單一的資料庫連接. 在開始處正確的開啟串連, 使用它直到結束, 最後關閉它. 不要像下面這樣在函數中開啟串連:

function add_to_cart() {$db = new Database(); $db->query("INSERT INTO cart ....."); } function empty_cart() {$db = new Database(); $db->query("DELETE FROM cart ....."); }

使用多個串連是個糟糕的, 它們會拖慢應用, 因為建立串連需要時間和佔用記憶體。特定情況使用單例模式, 如資料庫連接.。

這個秘籍是不是很精彩,相信一定對大家學習php程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.