您的位置:首页 > 编程语言 > PHP开发

Yii2-核心框架代码规范

2016-04-21 08:37 585 查看

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-核心框架代码规范
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: