搜尋
首頁後端開發php教程提高PHP程式碼品質的方法

提高PHP程式碼品質的方法

Mar 08, 2018 pm 02:27 PM
php方法品質

身為php程式設計師當然希望自己的PHP程式碼品質很高,本文主要和大家分享提升PHP程式碼品質的方法,希望能幫助大家。

1.不要使用相對路徑

常常會看到:

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

該方法有很多缺點:

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

因此會檢查過多路徑.

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

另一問題, 當定時任務運行該腳本, 它的上級目錄可能就不是工作目錄了.

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

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建議的部落格文章都沒提到這點.

<?phpecho "Hello";//Now dont close this tag

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

一個super_class.php 檔案

<?phpclass super_class{    function super_function()
    {        //super code
    }
}?>//super extra character after the closing tag

index.php

require_once(&#39;super_class.php&#39;);//echo an image or pdf , or set the cookies or session data

這樣, 你將會得到一個 Headers already send error. 為什麼? 因為 「super extra character」 已經被輸出了. 現在你得開始調試啦. 這會花費大量時間尋找 super extra 的位置.

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

<?phpclass super_class{    function super_function()
    {        //super code
    }
}//No closing tag

這會更好。

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

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

function print_header(){    echo "<p id=&#39;header&#39;>Site Log and Login links</p>";
}function print_footer(){    echo "<p id=&#39;footer&#39;>Site was made by me</p>";
}

print_header();for($i = 0 ; $i < 100; $i++)
{    echo "I is : $i <br />&#39;;
}
print_footer();

替代方案, 在某個地方集中收集輸出. 你可以儲存在函數的局部變數中, 也可以使用ob_start和ob_end_clean. 如下:

function print_header(){
    $o = "<p id=&#39;header&#39;>Site Log and Login links</p>";    return $o;
}function print_footer(){
    $o = "<p id=&#39;footer&#39;>Site was made by me</p>";    return $o;
}echo print_header();for($i = 0 ; $i < 100; $i++)
{    echo "I is : $i <br />&#39;;
}
echo print_footer();

為什麼需要輸出緩衝:

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

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

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

輸出一些xml.

$xml = &#39;<?xml version="1.0" encoding="utf-8" standalone="yes"?>&#39;;
$xml = "<response>
  <code>0</code>
</response>";//Send xml dataecho $xml;

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

$xml = &#39;<?xml version="1.0" encoding="utf-8" standalone="yes"?>&#39;;
$xml = "<response>
  <code>0</code>
</response>";//Send xml dataheader("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 "#p id { background:#000; }";

曾經遇過在mysql表中設定了unicode/utf-8編碼,  phpadmin也能正確顯示, 但當你取得內容並在頁面輸出的時候,會出現亂碼. 這裡的問題出在mysql連接的字符編碼.

//Attempt to connect to database$c = mysqli_connect($this->host , $this->username, $this->password);//Check connection validityif (!$c) 
{	die ("Could not connect to the database host: <br />". mysqli_connect_error());
}//Set the character set of the connectionif(!mysqli_set_charset ( $c , &#39;UTF8&#39; ))
{	die(&#39;mysqli_set_charset() failed&#39;);
}

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

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

php5.4前, 字元的預設編碼是ISO-8859-1, 不能直接輸出如À â等.

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

php5.4以后, 默认编码为UTF-8, 这將解决很多问题. 但如果你的应用是多语言的, 仍然要留意编码问题,.

以上是提高PHP程式碼品質的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
PHP中的依賴注入:一個簡單的解釋PHP中的依賴注入:一個簡單的解釋May 10, 2025 am 12:08 AM

依賴性(di)inphpenhancesCodeFlexibility andTestability by decouplingClassesscyclasses fromtheippentencies.1)UseConstructorientoctionTopAssDopassDectiesViactructors Viactructors

PHP DI容器比較:選擇哪一個?PHP DI容器比較:選擇哪一個?May 10, 2025 am 12:07 AM

推薦Pimple用於簡單項目,Symfony的DependencyInjection用於復雜項目。 1)Pimple適合小型項目,因其簡單和靈活。 2)Symfony的DependencyInjection適合大型項目,因其功能強大。選擇時需考慮項目規模、性能需求和學習曲線。

PHP依賴注入:什麼,為什麼以及如何?PHP依賴注入:什麼,為什麼以及如何?May 10, 2025 am 12:06 AM

依賴性注射(DI)InphpisadesignpatternwhereClassDepentenciesArepassedtotosedTosedTosedTotratherThancReateDinterally,增強codemodemodularityAndTestabily.itimprovessoftwarequalitybyby By:1)增強tosestabilityTestabilityTestabilityThroughityThroughEasyDepentyDepententymydependentymocking,2)增強Flexibilybya

PHP中的依賴注入:最終指南PHP中的依賴注入:最終指南May 10, 2025 am 12:06 AM

依賴性(di)InphpenhancesCodemodularity,可檢驗性和確定性。 1)itallowSeasysWappingOfComponents,AsseeninaPaymentGateWayswitch.2)dicanbeimimplementlededMermplemplemplemplemplemplemplemplemplempletallyororororerorviacontainers,withcontanersAddingComplexiteDcomplexiteDcomplexiteDcomplexitingCompleaDdingCompleAddingButaidLararArargerProprproproprys.3)

優化PHP代碼:減少內存使用和執行時間優化PHP代碼:減少內存使用和執行時間May 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP電子郵件:分步發送指南PHP電子郵件:分步發送指南May 09, 2025 am 12:14 AM

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自動化intifications andMarketingCampaigns.1)設置設置yourphpenvenvironnvironnvironmentwithaweberswithawebserverserververandphp,確保themailfunctionisenabled.2)useabasicscruct

如何通過PHP發送電子郵件:示例和代碼如何通過PHP發送電子郵件:示例和代碼May 09, 2025 am 12:13 AM

發送電子郵件的最佳方法是使用PHPMailer庫。 1)使用mail()函數簡單但不可靠,可能導致郵件進入垃圾郵件或無法送達。 2)PHPMailer提供更好的控制和可靠性,支持HTML郵件、附件和SMTP認證。 3)確保正確配置SMTP設置並使用加密(如STARTTLS或SSL/TLS)以增強安全性。 4)對於大量郵件,考慮使用郵件隊列系統來優化性能。

高級PHP電子郵件:自定義標題和功能高級PHP電子郵件:自定義標題和功能May 09, 2025 am 12:13 AM

CustomHeadersheadersandAdvancedFeaturesInphpeMailenHanceFunctionalityAndreliability.1)CustomHeadersheadersheadersaddmetadatatatatataatafortrackingandCategorization.2)htmlemailsallowformattingandttinganditive.3)attachmentscanmentscanmentscanbesmentscanbestmentscanbesentscanbesentingslibrarieslibrarieslibrariesliblarikelikephpmailer.4)smtppapapairatienticationaltication enterticationallimpr

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境