下面的代码样式用于Yii 2.x 核心和官方扩展开发.如果您想将请求代码拉入内核,请考虑使用它. 我们并不强迫您在应用程序中使用这种代码样式.你可以自由选择更适合你的.
你可以在这里获得CodeSniffer的配置: https://github.com/yiisoft/yii2-coding-standards
总体上我们使用 PSR-2 兼容的风格,所以一切适用 PSR-2 也适用于我们的代码样式.
<?php
或 <?=
标签.StudlyCaps
.camelCase
.camelCase
.elseif
而不是 else if
.<?php ?>
或 <?=
标签; 它不能使用其他标记变体,例如 <?
.?>
..php
结束.PHP 代码只能使用 UTF-8 没有 BOM 头.
类名 必须 在 StudlyCaps
. 例如, Controller
, Model
.
The term "class" refers to all classes and interfaces here.
CamelCase
./**
* 实例
*/
class MyClass extends \yii\base\BaseObject implements MyInterface
{
// 代码
}
类常量必须在所有带有下划线分隔符的大写字母中声明. 例如:
<?php
class Foo
{
const VERSION = '1.0';
const DATE_APPROVED = '2012-06-01';
}
public
keyword explicitly.$_varName
.$camelCase
第一个字母小写.$i
and $j
are better not to be used.例如:
<?php
class Foo
{
public $publicProp1;
public $publicProp2;
protected $protectedProp;
private $_privateProp;
public function someMethod()
{
// ...
}
}
camelCase
这样子的第一个字母小写.private
, protected
和
public
modifiers. var
是不允许的./**
* Documentation
*/
class Foo
{
/**
* Documentation
*/
public function bar()
{
// code
return $value;
}
}
@param
, @var
, @property
and @return
must declare types as bool
, int
, string
, array
or null
.
You can use a class names as well such as Model
or ActiveRecord
.ClassName[]
.isActive
, hasClass
, etc) the first line should start with Checks whether
.@return
should explicitly describe what exactly will be returned./**
* 检查IP是否在子网范围内
*
* @param string $ip 一个IPv4或IPv6地址
* @param int $cidr the CIDR lendth
* @param string $range subnet in CIDR format e.g. `10.0.0.0/8` or `2001:af::/64`
* @return bool IP是否在子网范围内
*/
private function inRange($ip, $cidr, $range)
{
// ...
}
__construct
应该使用PHP 4样式的构造函数.true
, false
, null
and array
.Changing type of an existing variable is considered as a bad practice. Try not to write such code unless it is really necessary.
public function save(Transaction $transaction, $argument2 = 100)
{
$transaction = new Connection; // bad
$argument2 = 200; // good
}
$str = 'Like this.';
$str1 = "Hello $username!";
$str2 = "Hello {$username}!";
以下内容是不允许的:
$str3 = "Hello ${username}!";
连接字符串时,在点周围添加空格:
$name = 'Yii' . ' Framework';
当字符串很长时,格式如下:
$sql = "SELECT *"
. "FROM `post` "
. "WHERE `id` = 121 ";
对于数组,我们使用PHP 5.4短数组语法.
在声明数组时使用以下格式:
$arr = [3, 14, 15, 'Yii', 'Framework'];
如果一行有太多的元素:
$arr = [
3, 14, 15,
92, 6, $test,
'Yii', 'Framework',
];
对关联数组使用以下格式:
$config = [
'name' => 'Yii',
'options' => ['usePHP' => true],
];
if ($event === null) {
return new Event();
}
if ($event instanceof CoolEvent) {
return $event->instance();
}
return null;
// 以下内容是不允许的:
if (!$model && null === $event)
throw new Exception('test');
Prefer avoiding else
after return
where it makes sense.
Use guard conditions.
$result = $this->getResult();
if (empty($result)) {
return true;
} else {
// process result
}
更好的
$result = $this->getResult();
if (empty($result)) {
return true;
}
// process result
为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;
}
doIt(2, 3);
doIt(['a' => 'b']);
doIt('a', [
'a' => 'b',
'c' => 'd',
]);
Note space between function
/use
tokens and open parenthesis:
// 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;
});
Refer to phpDoc for documentation syntax.
没有文档的代码是不允许的.
All class files must contain a "file-level" docblock at the top of each file and a "class-level" docblock immediately above each class.
There is no need to use @return
if method does return nothing.
All virtual properties in classes that extend from yii\base\BaseObject
are documented with an @property
tag in the class doc block.
These annotations are automatically generated from the @return
or @param
tag in the corresponding getter or setter by running ./build php-doc
in the build directory.
You may add an @property
tag
to the getter or setter to explicitly give a documentation message for the property
introduced by these methods when description differs from what is stated
in @return
. Here is an example:
<?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\BaseObject
/**
* 返回事件的附加事件处理程序列表.
* You may manipulate the returned [[Vector]] object by adding or removing handlers.
* 例如,
*
* ```
* $component->getEventHandlers($eventName)->insertAt(0, $eventHandler);
* ```
*
* @param string $name 事件名称
* @return 事件的附加事件处理程序的向量列表
* @throws 如果没有定义事件的报错为Exception
*/
public function getEventHandlers($name)
{
if (!isset($this->_e[$name])) {
$this->_e[$name] = new Vector;
}
$this->ensureBehaviors();
return $this->_e[$name];
}
As you can see in the examples above we use markdown to format the phpDoc comments.
There is additional syntax for cross linking between classes, methods and properties in the documentation:
[[canSetProperty]]
will create a link to the canSetProperty
method or property of the same class.[[Component::canSetProperty]]
will create a link to canSetProperty
method of the class Component
in the same namespace.[[yii\base\Component::canSetProperty]]
will create a link to canSetProperty
method of the class Component
in namespace yii\base
.[[Component]]
will create a link to the Component
class in the same namespace. Adding namespace to the class name is also possible here.To give one of the above mentioned links another label than the class or method name you can use the syntax shown in the following example:
... as displayed in the [[header|header cell]].
The part before the | is the method, property or class reference while the part after | is the link label.
It is also possible to link to the Guide using the following syntax:
[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
,比如对当前实现的递归调用,而不是扩展类实现.Properties allowing to configure component not to do something should accept value of false
. null
, ''
, or []
should not be assumed as such.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。