5.1 类型 所有PHP类型和值都应该使用小写。这包括true、false、null和array。//好吧,有时候NULL会用大写,改正 更改现有变量的类型被认为是一种不好的实践。除非确实需要,否则不要编写这样的代码。//虽然php是弱类型,语法上并没有问题,但是确实会反应我的编码习惯甚至技术水平
public function save(Transaction $transaction, $argument2 = 100) { $transaction = new Connection; // bad 跟上面的参数类型不一致 $argument2 = 200; // good }
5.2 字符串 如果字符串不包含变量或单引号,则使用单引号 // 这个是从性能上考虑的,单引号执行速度更快
$str = 'Like this.';
[单双引号的各有适用场景,具体见两者的区别] 如果字符串包含单引号,可以使用双引号来避免额外的转义。 变量替换 [Variable substitution]
$str1 = "Hello $username!"; $str2 = "Hello {$username}!";
以下内容是不允许的:
$str3 = "Hello ${username}!"; // 不允许,但还是会正常解析执行
连接 连接字符串时,在圆点【.】周围添加空格:
$name = 'Yii' . ' Framework'; // 一向如此,美观
当字符串很长时,格式如下: // 了解了
$sql = "SELECT *" . "FROM `post` " . "WHERE `id` = 121 ";
5.3 数组 对于数组,我们使用PHP 5.4短数组【即[ ]】语法。 数值索引 不要使用负数作为数组索引。// 还是没试过,似乎会转化为自然数? 答案:并不会
$test = [-1=>1,-2=>2]; var_dump($test);
输出: array(2) { [-1]=> int(1) [-2]=> int(2) }
在声明数组时使用以下格式:
$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');
更应该避免在return之后使用 else。使用 guard conditions // [涉及的写法,确实困惑过,还是有点困惑]
$result = $this->getResult(); if (empty($result)) { return true; } else { // process result }
// 要比下面的好
$result = $this->getResult(); if (empty($result)) { return true; }
// process result
Replace Nested Conditional with Guard Clauses【用保护子句替换嵌套条件句】
// 嵌套条件句 function getPayAmount() { let result; if (isDead) result = deadAmount(); else { if (isSeparated) result = separatedAmount(); else { if (isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; }
// 保护子句 推荐使用 function getPayAmount() { if (isDead) return deadAmount(); if (isSeparated) return separatedAmount(); if (isRetired) return retiredAmount(); return normalPayAmount(); }
开关[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) { //可以看到function 和 use 左右都是有空格的 $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; });
文档 [再说][均可以借助IDE模仿来写,而且有时候也不是必须要写的] 有关文档语法,请参考phpDoc。 没有文档的代码是不允许的。 所有类文件都必须在每个文件的顶部包含一个“文件级”docblock,并且在每个类的上面立即包含一个“类级”docblock。 如果方法不返回任何东西,就不需要使用@return。// 好吧,这时我总会返回true 扩展自yii\base\BaseObject的类中的所有虚拟属性都用类doc块中的@property标记记录下来。通过在build目录中运行./build php-doc,可以从相应的getter或setter中的@return或@param标记自动生成这些注释。您可以向getter或setter添加@property标记,以便在描述与@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)
File
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */
Class
/** * 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
Function / method
/** * 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 【省略】 Comments【注释】
一行注释,应该以 // 而不是#开头。 一行注释,应该在它自己的行上。// 理应如此
额外规则【Additional rules】
=== [] vs . empty() 尽可能使用empty()。
多个返回点 【multiple return points】
当嵌套条件开始变得混乱时,尽早返回。如果方法很短,也没有关系。
self vs. static
除下列情况外,请始终使用 static: 访问常量必须通过self: self::MY_CONSTANT来完成 访问私有静态属性必须通过self: self::$_events来完成 它允许在有意义的方法调用中使用self,例如对当前实现的递归调用,而不是扩展类实现。
用于“不要做某事”的值 【value for "don't do something"】
允许配置组件不做某些事情的属性应该接受false值。不应该假定为null、''或[]。
目录/命名空间名称【Directory/namespace names】
使用小写 用复数形式表示表示对象的名词(e.g. validators) 使用单数形式表示相关功能/特性的名称(例如web) 更喜欢单字名称空间 // 优先选择 如果单个单词不合适,使用camelCase【小驼峰】// 待了解
|