PHP – 編碼規範 v1.0

多釐發表於2019-02-16

一、 命名規則

1. 命名規則概要

1) 使用含義豐富的名字

# good
if ($currentYear > 2009) ...

# bad
if($t > 2009) ...    

2) 在縮寫中,只將首字母大寫

# good
function getHttpHost()

#bad
function getHTTPHost()    

2. 類命名

1) 類應該以名詞單數形式, 首字母大寫, 大小寫混排,方式命名

class SqlStatement {    ...    }

2) 表示一組事物的類應使用複數形式

class SqlStatements {    ...    } 

3) 型別開頭要比以型別結尾更容易識別
對一個已知型別的變數來說, 其名稱以型別開頭要比以型別結尾更容易識別

class ErrorConnection extends Error {
    // ...    
}     

$arrCatids = array(1,2,3,4,5,6);
$strCatids = ‘1,2,3,4,5,6’; 

4) 介面的預設實現類可以以Default開頭

class DefaultSqlBuilder extends ISqlBuilder {
    //...    
} 

3. 介面命名

介面的名字應為以字母”I”開頭的名詞或形容詞

interface ISqlEngine{}    interface ISortable{}

4. 變數/屬性命名

1) 屬性名應以小寫字母開頭, 採用駝峰法則.

public $userAuth;

3) 常量的名字必須全部為大寫字母
所有字母大寫,單詞之間用下劃線分割

const SEARCH_GOOGLE = 1;    
const SEARCH_YAHOO  = 2;

4) 命名一組物件時,應使用複數形式

public $books;

5) 布林型變數不應使用否定性名字

# good
public $isFound;    
public $isEnough;

# bad
public $isNotFound;    
public $isNotEnough;

6) 在巢狀迴圈中,使用有意義豐富的名字來命名迴圈控制變數

# good
for($row = 0; $i < getRows();$row++) {    
    for($col= 0;$j < getCols(); $col++) {
        // ...    
    }    
}

# bad
for($i = 0; $i < getRows();$i++) {
    for($j= 0;$j < getCols(); $j++){
        // ...    
    }    
}

7) 傳入的變數採用蛇形寫法, 自定義函式變數採用蛇形寫法

# 控制器變數
class UserController extends Controller{
    function postLogin(Request $request) {
        // 這裡是蛇形寫法
        $order_status = $request->input(`order_status`);
    }
}

# 自定義函式變數
# 這裡傳入的變數採用蛇形寫法
function route_url($route, $params, $option_params){
    // ...
}

5. 函式命名

禁止拼音命名法

1) 類函式名稱以小寫字母開頭, 採用駝峰法則

function getCurrentYear()

2) 用動詞命名函式

# 動詞表:
add / edit / remove 
begin / end
create / destroy
first / last 
get / release
get / set
increment / decrement
put / get
lock / unlock 
open / close
min / max 
old / new 
start / stop
next / previous 
source / target 
show / hide
send / receive
cut / paste 
up / down

# 系詞表:
is / has
function startDatabase()
function getDatabaseStatus()

3) 函式名字可以忽略類或物件名稱,以避免重複

# good
class Font {
    function getFamily();
}

# bad
class Font {    
    function getFontFamily();
}

4) 單例類應該通過一個名為getInstance()的靜態函式返回他們唯一的值

class Toolkit {    
    private static const toolkit = new Toolkit();
    public static function getInstance(){
        return toolkit; 
    }    
} 

二、 檔案格式/ 技巧

1. 留白

恰當的使用空格可以有效提高程式碼的可讀性

1) 使用空格的通用規則

  1. 操作符,冒號的前後都應有一個空格.

  2. 逗號,分號之後須有一個空格

# good
$bit = $bitStart + $bitEnd;
case `someStr` :
mysqlConnection($config, $dbname);
if($count > 9)

#bad
$bit=$bitStart+$bitEnd;    
case `someStr`:    
mysqlConnection($config,$dbname);
if($count>9)    

2) 邏輯單元應該以空行分割

function drawCapture() {    
    $chars = getChars(5);
    
    // imageCreate
    $img = imageCreate();
    
    // output image
    outputImage();    
} 

2. 控制流程

1) for,while,if語句格式如下

# for
for (init; condition; update) {    
    // ...    
} 

# while
while (condition) {    
    // ...    
} 

# if
if (condition) {
    // ...    
} else if (condition) {    
    // ...    
} else {
    // ...    
} 

2) 迴圈/條件語句必須以 ‘{‘ , ’}’巢狀

# good
if ($i > 0) {
    $val ++;    
}
for ($i = 0; $i < $size; $i++) {    
    $val ++;    
}

# bad 
for($i=0; $i<$size; $i++)    $val ++;
if($i > 0)    $val ++;

3) 使用臨時變數以避免複合條件語句

# good
$itemValid = $itemMoney > 800 && $level > 3 && $valid > 0;
if($itemValid && isReady()) {
    display();    
}

# bad
if($itemMoney > 800 && $level > 3 && $valid > 0 && isReady()) {    
    display();    
}

4) Switches 語句應該套用以下格式,並且每個分支必須註釋清楚

switch (condition) {
    case 0:            
    // show something
        break;    
    default:
    // this is some code
}

3. 宣告

1) 類/介面宣告順序
類文件中的語句的順序.

1.    文件/註釋
2.    類/介面語句
3.    常量
4.    靜態變數順序:[public, protected, (default), private]
5.    例項變數順序:[public, protected, (default), private]
6.    建構函式 __construct();
7.    函式 function;

2) 變數的宣告要在程式碼塊的開頭,而不是在用到它們的地方

public function method() {
    $value = 0;
    ...    
    for (...) {    
        $value += $num;    
    }    
} 

4. 技巧

刪除檔案尾部的 ?>

php檔案的典型標記是以 <?php開頭, ?>結尾。但是在Zend Framework中卻不推薦在php檔案末尾加 ?>
因為在<?php ?>之外的任何字元都會被輸出到網頁上,而之中的卻不會。所以在末尾不加?>可以預防php檔案被惡意加入字元輸出到網頁。

陣列的鍵名

在PHP中, 使用不經單引號包含的字串作為陣列鍵名是合法的, 但是我們不希望如此 — 鍵名應該總是由單引號包含而避免引起混淆. 注意這是使用一個字串, 而不是使用變數做鍵名的情況

// 錯誤    
$foo = $assoc_array[blah];
// 正確
$foo = $assoc_array[`blah`];
// 錯誤
$foo = $assoc_array["$var"];
// 正確    
$foo = $assoc_array[$var]; 

不要使用未初始化的變數

// 錯誤    
if ($forum) ...
// 正確
if (isset($forum)) ...
// 正確    
if (isset($forum) && $forum == 5) 

避免在大陣列上使用 in_array()

避免在大的陣列上使用 in_array(), 同時避免在迴圈中對包含200個以上元素的陣列使用這個函式. in_array()會非常消耗資源. 對於小的陣列這種影響可能很小, 但是在一個迴圈中檢查大陣列可能會需要好幾秒鐘的時間. 如果您確實需要這個功能, 請使用isset()來查詢陣列元素. 實際上是使用鍵名來查詢鍵值. 呼叫 isset($array[$var]) 會比 in_array($var, array_keys($array)) 要快得多.

SQL 指令碼格式

SQL 程式碼常常會變得很長, 如果不作一定的格式規範, 將很難讀懂. SQL程式碼一般按照以下的格式書寫, 以關鍵字換行:

$sql = `SELECT *     
<-one tab->FROM ` . SOME_TABLE . ` 
<-one tab->WHERE a = 1 
<-two tabs->AND (b = 2 
<-three tabs->OR b = 3)     
<-one tab->ORDER BY b`; 

這裡是應用了製表符後的例子:

$sql = `SELECT *
    FROM ` . SOME_TABLE . ` 
    WHERE a = 1 
        AND (b = 2 
            OR b = 3)        
    ORDER BY b`;     

禁止使用單字母開頭的變數

$tKey, $tVal

5. 空行的使用

  • <?php 之後必須有1個空行

  • 兩個函式之間必須有1個空行。

  • return、die、exit之前如果有其他語句的情況下應加上一個空行

三、 文件與註釋

1. PHPDoc

PHPDoc 是一個 PHP 版的 Javadoc。它是一種註釋 PHP 程式碼的正式標準。它支援通過類似 phpDocumentor 這樣的外部文件生成器生成 API 文件,也可以幫助一些例如 Zend Studio, NetBeans, ActiveState Komodo Edit and IDE 和 Aptana Studio 之類的 整合開發環境 理解變數型別和弱型別語言中的其他歧義並提供改進的程式碼完成,型別提示和除錯功能。
參考地址: http://zh.wikipedia.org/zh/PH…

2. 註釋

註釋類

/**
 * 這是某個類的介紹
 */    
class SomeClass{}

註釋區域性變數

function someFunction(){    
    var $result;          //獲取到的結果集
    var $searchResult;   //獲取到的搜尋結果集    
    // ...
}

註釋變數

/** @var name string */
public $name 

註釋函式
註釋的標記應按照以下順序

*     @param
*     @return
*     @see

3. PHP文件頭部註釋

/**
 * 檔案頭部說明
 * 
 * @author     Mark (zhaody901@126.com)
 * @copyright  Copyright (c) 2014-2016 sour-lemon team
 */

框架常用命名

控制器方法

getIndex()     # 列表
getCreate()    # 建立
postCreate()   # 儲存建立
getEdit()      # 編輯
postEdit()     # 儲存編輯
postUpdate()   # 批量更新
postDelete()   # 刪除到回收站
postDestroy()  # 徹底刪除

附錄Appendices

附錄A:參考文件

附錄B:PHPDoc 標籤參考

線上版地址 : http://manual.phpdoc.org/HTML…

@abstract        Documents an abstract class, class variable or method.
@access    public, private or protected    Documents access control for an element. @access private indicates that documentation of element be prevented.
@author    author name <author@email>    Documents the author of the current element.
@category        Specify a category to organize the documented element’s package into
@copyright    name date    Documents copyright information.
@deprecated    version    Documents a method as deprecated.
@example    /path/to/example    Documents the location of an external saved example file.
@exception        documents an exception thrown by a method — also see @throws.
@global    type $globalvarname    Documents a global variable or its use in a function or method.
@ignore        Prevents the documentation of an element
@internal        private information for advanced developers
@link    URL    
@name    global variable name    Specifies an alias for a variable. For example, $GLOBALS[‘myvariable’] becomes $myvariable
@magic        phpDocumentor tags}-.
@package    name of a package    Documents a group of related classes and functions.
@param    type [$varname] description    
@return    type description    This tag should not be used for constructors or methods defined with a void return type.
@see        Documents an association to another method or class.
@since    version    Documents when a method was added to a class.
@static        Documents a static class or method
@staticvar        Documents a static variable’s use in a function or class
@subpackage        
@throws        Documents an exception thrown by a method.
@todo        Documents things that need to be done to the code at a later date.
@var    type    a data type for a class variable
@version        Provides the version number of a class or method.

附錄C: 版本變化

v1.4(2016年10月07日)

更改為markdown格式, 並且將其替換為Laravel 編碼格式

V1.3(2015年4月19日)

專案檔案結構說明

V1.2(2013年4月27日)

分離專案公共部分

V1.1(2013年4月2日)

增加左格式化內容
增加刪除 ?> 標記

V1.0(2012年11月7日)

初始化規範

相關文章