當前位置:才華齋>計算機>php語言>

提高PHP程式碼質量的技巧

php語言 閱讀(3.12W)

PHP程式碼質量該怎麼提高?相信這是大多數PHP新手想了解的,下面小編給大家介紹PHP效能優化小技巧,歡迎閱讀!

提高PHP程式碼質量的技巧
  提高PHP程式碼質量的技巧

 1.不要使用相對路徑

常常會看到:

require_once('../../lib/some_');

該方法有很多缺點:

它首先查詢指定的php包含路徑, 然後查詢當前目錄.

因此會檢查過多路徑.

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

另一問題, 當定時任務執行該指令碼, 它的上級目錄可能就不是工作目錄了.

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

view sourceprint?

define('ROOT' , '/var/www/project/');

require_once(ROOT . '../../lib/some_');

//rest of the code

我們定義了一個絕對路徑, 值被寫死了. 我們還可以改進它. 路徑 /var/www/project 也可能會改變, 那麼我們每次都要改變它嗎? 不是的, 我們可以使用__FILE__常量, 如:

//suppose your script is /var/www/project/

//Then __FILE__ will always have that full path.

define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));

require_once(ROOT . '../../lib/some_');

//rest of the code

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

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

可以在指令碼頭部引入多個檔案, 像類庫, 工具檔案和助手函式等, 如:

require_once('lib/');

require_once('lib/');

require_once('helpers/utitlity_');

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

function load_class($class_name)

{

//path to the class file

$path = ROOT . '/lib/' . $class_name . '');

require_once( $path );

}

load_class('Database');

load_class('Mail');

有什麼不一樣嗎? 該程式碼更具可讀性.

將來你可以按需擴充套件該函式, 如:

function load_class($class_name)

{

//path to the class file

$path = ROOT . '/lib/' . $class_name . '');

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("" , $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_ 檔案

<?php

class super_class

{

function super_function()

{

//super code

}

}

?>

//super extra character after the closing tag

require_once('super_');

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

JavaScript

header("content-type: application/x-javascript");

echo "var a = 10";

CSS

header("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)&nbsp;

{

die ("Could not connect to the database host: ". mysqli_connect_error());

}

//Set the character set of the connection

if(!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"]

PHP原始為Personal Home Page的縮寫,已經正式更名為 "PHP: Hypertext Preprocessor"的縮寫。下面小編給大家介紹PHP程式效能優化的方法,歡迎閱讀!

php實現的簡單中文驗證碼功能示例

<?php

session_start();

/*for($i=0;$i<4;$i++) {

$rand .= dechex(rand(1,15));

}

$_SESSION[check_pic] = $rand;

*/

$image = imagecreatetruecolor(100, 30);

$bg = imagecolorallocate($image, 0, 0, 0);

$color = imagecolorallocate($image, 255, 255, 255);

//imagestring($image, rand(1,6), rand(3,60),

rand(3,15), $rand, $color);

for($i=0;$i<3;$i++) {

$color2 = imagecolorallocate($image, rand(0,255),

rand(0,255),rand(0,255));

imageline($image, rand(0,100), 0, 100, 30, $color2);

}

//rand() ---->0-max 不大於100

for($i=0;$i<200;$i++) {

imagesetpixel($image, rand()%100, rand()%30,

$color2);

}

//$str = iconv("gbk", "utf-8", "中");

$str = "中國";

$_SESSION[check_pic] = $str;

//解決中文,頁面本身為utf-8

$str = mb_convert_encoding($str, "html-entities",

"utf-8" );

//2:字型大小 3:傾斜角度 x , y 座標

imagettftext($image, 12, 0, 20, 20, $color,

'', $str);

//輸出圖片

header("Content-type: image/jpeg;charset=utf-8");

imagejpeg($image);

/*修改eclipse的配置,可以使得eclipse的新建專案的

預設編碼直接為UTF-8

在選單欄的

Window->Preferences->General->Workspace

->Text file encoding

將其改為UFT-8即可。*/

?>

<?php

header("Content-type: text/html;charset=utf-8");

session_start();

if($_POST[check]) {

if($_POST[check]==$_SESSION[check_pic]) {

echo "驗證碼正確:".$_SESSION[check_pic];

} else {

echo "驗證碼錯誤:".$_SESSION[check_pic];

}

}

?>

<form action="" method="post">

<img alt="" src=""><br/>

<input type="text" name="check"><br/>

<input type="submit" value="提交">

</form>