1.概述
簡單說,我們使用PSR-2兼容規范,所以應用於PSR-2的一切對我們的代碼也同樣適用。
- 文件必須使用 <?php 或 <?= 標簽。
- 文件未尾應該有一個新行。
- PHP代碼文件必須只能使用無BOM的UTF-8。
- 代碼縮進必須使用4個空格,而不是tab按鍵。
- 類名必須使用大駝峰式(首字母大寫)聲明。
- 類中常量必須使用全大寫帶下划線方式聲明。
- 方法名稱必須使用小駝峰式(首字母小寫)聲明 。
- 屬性名稱必須使用小駝峰式(首字母小寫)聲明。
- 如果是私有屬性名,必須使用下划線開始。
- 使用elseif代替else if。
2.文件
2.1.PHP標簽
- PHP代碼必須使用 <?php 或 <?= 標簽;一定不能使用其它的標簽名,如<?。
- 如果文件中僅有PHP,它不應該以?>結尾。
- 不要在文件尾添加尾空格。
- 任何包括PHP代碼的文件均應該以.php為后綴。
2.2.字符編碼
PHP代碼文件必須只能使用無BOM的UTF-8。
3.類名
類名必須使用大駝峰式(首字母大寫)聲明。例如,Controller,Model。
4.類
這里的"類"涉及所有的類和接口。
- 類應該使用大駝峰式(首字母大寫)方式來命名。
- 括號應該寫在類名下方。
- 每個類必須要有符合PHPDoc的文檔部分。
- 在類中的所有代碼必須只有一個獨立縮進tab。
- 一個PHP文件中僅應該有一個類。
- 所有的類均應該存在命名空間。
- 類名匹配文件名。類命名空間應該匹配字典結構。
/**
* Documentation
*/
class MyClass extends \yii\Object implements MyInterface
{
// code
}
4.1.常量
類中常量必須使用全大寫帶下划線方式聲明。例如:
<?php
class Foo
{
const VERSION = '1.0';
const DATE_APPROVED = '2012-06-01';
}
4.2.屬性
- 當聲明公共類成員時,要特別明確關鍵字public。
- 公有和保護變量應該在任何方法聲明前被聲明。私有變量可以在類頂部聲明,但也可添加在關聯的類方法字塊使用之前。
- 類中的屬性聲明順序應該是從公有、保護到私有。
- 為了增強可讀性,屬性聲明間沒有空行且在屬性和方法聲明間有兩個空行。
- 私有變量應該像如此命名$_varName。
- 公共類成員和獨立變量應該這樣首字母小寫命名$camelCase。
- 使用描述命名。變量最好不要使用$i和$j來命名。
例如:
<?php
class Foo
{
public $publicProp;
protected $protectedProp;
private $_privateProp;
}
4.3.方法
- 函數和方法應該命名使用首字母小寫的小駝峰式。
- 名字應該體現函數所實現的功能描述。
- 類方法中應該經常可見private,protected和public的修飾。var是不允許的。
- 方法的開括號應該在方法下方。
/**
* Documentation
*/
class Foo
{
/**
* Documentation
*/
public function bar()
{
// code
return $value;
}
}
4.4.文檔塊
參數,變量,屬性和返回值必須聲明類型,如boolean,integer,string,array或null。你也可以使用類名,像Model或ActiveRecord。如:對於一個數組類型可以使用ClassName[]。
4.5.構造方法
- _construct應該使用PHP 4的構造方法。
5. PHP
5.1.數據類型
- 所有的數據類型和變量均應該小寫。包括true,false,null和array。
改變已有的數據類型是不推薦的。除非你必須要寫這樣的代碼。
public function save(Transaction $transaction, $argument2 = 100)
{
$transaction = new Connection; // bad
$argument2 = 200; // good
}
5.2. 字符串
- 如果字符串中不包括變量或單引號時,請使用單引號。
$str = 'Like this.';
- 如果字符串中有單引號,你可以使用雙引號來避免額外的轉義。
變量替換
$str1 = "Hello $username!";
$str2 = "Hello {$username}!";
下面的方式是不允許的:
$str3 = "Hello ${username}!";
連接
連接字符串時,使用點在空格周圍。
$name = 'Yii' . ' FrameWork';
長內容的字符串可以使用下面的方法:
$sql = "SELECT *"
. "FROM `post` "
. "WHERE `id` = 121 ";
5.3. 數組
對於數組,我們使用PHP 5.4中的短數組語法。
數字索引
- 不要使用負數作為索引。
使用下面的方法來聲明數組:
$arr = [3,14,15,'Yii','FrameWork'];
如果有太多的元素時,可單獨分行:
$arr = [
3, 14, 15,
92, 6, $test,
'Yii', 'Framework',
];
關聯
使用下面的格式來關聯數組:
$config = [
'name' => 'Yii',
'options' => ['usePHP' => true],
];
5.4. 控制語句
- 控制語句的條件必須有一個獨立的空格在前后的插入句。
- 操作符的括號內應該用空格間隔。
- 開括號跟控制語句在同一行中。
- 關括號應該是新起一行。
- 針對只有一行的語句也使用括號。
if ($event === null) {
return new Event();
}
if ($event instanceof CoolEvent) {
return $event->instance();
}
return null;
// the following is NOT allowed:
if (!$model && null === $event)
throw new Exception('test');
盡量避免當語句生效時,else在return之后。使用防衛條件。
$result = $this->getResult();
if (empty($result)) {
return true;
} else {
// process result
}
要優於:
$result = $this->getResult();
if (empty($result)) {
return true;
}
// process result
switch語句
switch使用下面的格式:
switch ($this->phpType) {
case 'string':
$a = (string) $value;
break;
case 'integer':
case 'int':
$a = (int) $value;
break;
case 'boolean':
$a = (bool) $value;
break;
default:
$a = null;
}
5.5. 函數調用
doIt(2, 3);
doIt(['a' => 'b']);
doIt('a', [
'a' => 'b',
'c' => 'd',
]);
5.6. 匿名函數(lambda)聲明
使用空格在function/use參數和語句之前:
// good
$n = 100;
$sum = array_reduce($numbers, function ($r, $x) use ($n) {
$this->doMagic();
$r += $x * $n;
return $r;
});
// bad
$n = 100;
$mul = array_reduce($numbers, function($r, $x) use($n) {
$this->doMagic();
$r *= $x * $n;
return $r;
});
文檔
- 參考phpDoc文檔語法。
- 沒有文檔的代碼是不允許的。
- 所有的類文件必須包括一個文件級別的文檔塊,在每一個文件中。並且,類級別的文檔塊直接在每一個類上方。
- 如果方法不返回任何內容時,不需要使用@return。
- 類中的所有繼承自yii\base\Object的虛屬性,在類文檔塊中被標記為@property。這些注釋被自動從getter和setter運行./bulid php-doc時的@return和@param生成。你可以添加一個@property標記到getter或setter,強制給一個屬性的信息介紹,在描述不同於剛開始的@return。下面是個例子:
<?php
/**
* Returns the errors for all attribute or a single attribute.
* @param string $attribute attribute name. Use null to retrieve errors for all attributes.
* @property array An array of errors for all attributes. Empty array is returned if no error.
* The result is a two-dimensional array. See [[getErrors()]] for detailed description.
* @return array errors for all attributes or the specified attribute. Empty array is returned if no error.
* Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:
* ...
*/
public function getErrors($attribute = null)
文件
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
類
/**
* Component is the base class that provides the *property*, *event* and *behavior* features.
*
* @include @yii/docs/base-Component.md
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Component extends \yii\base\Object
函數/方法
/**
* Returns the list of attached event handlers for an event.
* You may manipulate the returned [[Vector]] object by adding or removing handlers.
* For example,
*
* ~~~
* $component->getEventHandlers($eventName)->insertAt(0, $eventHandler);
* ~~~
*
* @param string $name the event name
* @return Vector list of attached event handlers for the event
* @throws Exception if the event is not defined
*/
public function getEventHandlers($name)
{
if (!isset($this->_e[$name])) {
$this->_e[$name] = new Vector;
}
$this->ensureBehaviors();
return $this->_e[$name];
}
標簽(Markdown)
正如你上面例子中看到的,我們使用標簽來格式phpDoc的內容。
下面是另外的語法用於類、方法和屬性之間在文檔中的連接:
- '[[canSetProperty]]'用於創建一個連接在canSetProperty方法或屬性在相同的類中。
- '[[Component::canSetProperty]]'用於創建一個連接在相同的命名空間內Component類中canSetProperty方法。
- '[[yii\base\Component::canSetProperty]]'用於創建一個連接在yii\base命名空間內Component類中canSetProperty方法。
為了給上面提到的連接其它的標簽類或方法名,你可以使用下面的語法:
... as displayed in the [[header|header cell]].
當|之后是連接標簽時,在|之前的是方法,屬性或類相關。
當然也可以連接到引導,使用下面的代碼:
[link to guide](guide:file-name.md)
[link to guide](guide:file-name.md#subsection)
注釋
- 單行注釋可使用//開始,而不是#。
- 單行注釋僅當前行有效。
其它規則
=== [] VS empty()
盡可能使用empty()。
多個返回點
當條件嵌套比較混亂時,盡早返回。如果方法比較簡短時,沒有關系。
self vs static
堅持使用static除非出現下面的場景:
- 獲取常量必須通過self:self::MY_CONSTANT
- 獲取私有屬性必須通過self:self::$_events
- 可以使用self來遞歸調用當前實現,代替擴展類的實現。
value for "don't do something"
屬性可以通過配制組件來接收false,null,''或[]值來不做一些事情。
字典/命名空間名
- 使用小寫字母
- 代表對象時,使用復數的形式(如,validators)
- 代表相關功能或特性時,使用單數的形式(如,web)Yii2-核心框架代碼規范
