资讯专栏INFORMATION COLUMN

PHP - 编码规范 v1.0

NickZhou / 860人阅读

摘要:所以在末尾不加可以预防文件被恶意加入字符输出到网页。它是一种注释代码的正式标准。

一、 命名规则 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) 使用空格的通用规则

操作符,冒号的前后都应有一个空格.

逗号,分号之后须有一个空格

# 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文件的典型标记是以 结尾。但是在Zend Framework中却不推荐在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. 空行的使用

两个函数之间必须有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:参考文档

PHPBB 编码规范
http://www.phpbbchina.com/wik...编码规范

Typecho PHP 编码规范
https://code.google.com/p/typ...

优化编写代码过程中的PHP
http://www.yeeyan.org/article...

附录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     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日)

初始化规范

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/25723.html

相关文章

  • 基于PSR-0编码规范开发一套PHP-MVC框架(二)

    摘要:框架采用编码规范开发的一套框架,纯面向对象开发,依赖包管理模版引擎数据库类错误输出等在项目根目录下使用命令执行安装插件二入口文件。引入文件,开启错误提示插件三数据库配置文件。视图模版不存在七控制器操作数据并显示到页面。 一、composer依赖包管理工具。composer.json { name:PHP-FRAME, author:Guoming.Zhang, ...

    graf 评论0 收藏0
  • Web安全开发规范手册V1.0

    摘要:一背景团队最近频繁遭受网络攻击,引起了技术负责人的重视,笔者在团队中相对来说更懂安全,因此花了点时间编辑了一份安全开发自检清单,觉得应该也有不少读者有需要,所以将其分享出来。 一、背景 团队最近频繁遭受网络攻击,引起了技术负责人的重视,笔者在团队中相对来说更懂安全,因此花了点时间编辑了一份安全开发自检清单,觉得应该也有不少读者有需要,所以将其分享出来。 二、编码安全 2.1 输入验证 ...

    Yuqi 评论0 收藏0
  • Web安全开发规范手册V1.0

    摘要:一背景团队最近频繁遭受网络攻击,引起了技术负责人的重视,笔者在团队中相对来说更懂安全,因此花了点时间编辑了一份安全开发自检清单,觉得应该也有不少读者有需要,所以将其分享出来。 一、背景 团队最近频繁遭受网络攻击,引起了技术负责人的重视,笔者在团队中相对来说更懂安全,因此花了点时间编辑了一份安全开发自检清单,觉得应该也有不少读者有需要,所以将其分享出来。 二、编码安全 2.1 输入验证 ...

    Ryan_Li 评论0 收藏0
  • imi v1.0 正式版,专注单体应用的 PHP 协程应用开发框架

    摘要:年开发并发布框架现已停止维护。经过一年实战,年月日,一周年之际正式发布版本。宇润部分开源项目我已通过码云平台,向项目力所能及地捐款,聊表心意。所以,目前主打的还是单体应用开发。协议的开发,也是带来的一大优势。 imi 介绍 showImg(https://segmentfault.com/img/bVbuab9?w=291&h=187); imi 是基于 PHP 协程应用开发框架,它支...

    genefy 评论0 收藏0
  • PHP 标准规范

    摘要:标准规范简介是的简写,由组织制定的规范,是开发的实践标准。具体标准有有了统一编码风格规范,更有利于查看和学习各个框架或类库,不不需要每次都适应新的编码风格。同时在开发团队内部使用统一的编码规范更有利于代码审查版本控制团队内部交流。 PHP 标准规范 PSR PSR 简介 PSR 是 PHP Standard Recommendations 的简写,由 PHP FIG 组织制定的 PHP...

    FuisonDesign 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<