记录PHP编码规范

原文链接:https://blog.csdn.net/qq_34827048/article/details/78666844

 

PHP编码规范

版权声明

每一个文件包含版权声明信息,具体格式如下

/**
 * 一行说明本文件的功能
 *
 * 如有必要,请详细说明本文件的具体内容和实现,可以多行。
 *
 * @category   Controller|Service|Template|Model|Middleware
 * @package    包名称
 * @author     张三 <zhangsan@-inc.com>
 * @copyright  2019 (C) 某某科技有限公司
 * @version    SVN: $Id$
 * @since      v1.0 引入文件时
 * @deprecated v1.1 弃用了本文件
 */

本编码规范大部分遵循PSR-2中的规范
基本

  •     所有PHP文件 必须 使用 Unix LF (linefeed) 作为行的结束符,且文件以UTF-8编码无BOM格式保存。
  •     所有PHP文件 必须 以一个空白行作为结束。
  •     纯PHP代码文件 必须 省略最后的 ?> 结束标签。
  •     每一行末尾不许有空格和tab的空白字符。
  •     每一行尽可能不超过80个字符,但绝对不可以超过120个字符。
  •     四个空格的方式缩进,不允许使用tab进行缩进
  •     PHP所有 关键字 必须 全部小写。常量 true 、false 和 null 也 必须 全部小写。

命名规范

  •     常量 Const:全部大写,单词之间使用下划线(_)连接,如PHP_CONST_VAR
  •     类 Class: 采用单词首字母大写的驼峰命名,中间无空格和连接符的方式,如ClassNameExample
  •     方法 Method: 采用首单词小写开头驼峰命名,第二及之后的单词首字母大写,如methodNameExample
  •     属性 Property: 全部采用小写,单词直接使用下划线(_),下划线分隔式,如class_property_example

Laravel 项目中的规范

  •     Controller中的方法,尽可能使用Requests文件的方式来定义请求权限和验证,但都必须使用(Request $request)参数接收 HTTP Request提交的内容。
  •     代码中不允许使用$_GET和$_POST接受HTTP Request的提交的内容。
  •     设计模式上要严格遵从Laravel的MVC框架,避免直接的DB::table操作
  •     涉及到对Model数据更新的操作应该走仓库设计模式Repository

代码注释

  • PHP项目中全部使用PHPDoc的编写方式,例子

class DateTimeHelper
{
    /**
     * @param mixed $anything Anything that we can convert to a \DateTime object
     *
     * @throws \InvalidArgumentException
     *
     * @return \DateTime
     */
    public function dateTimeFromAnything($anything)
    {
        $type = gettype($anything);

        switch ($type) {
            // Some code that tries to return a \DateTime object
        }

        throw new \InvalidArgumentException(
            "Failed Converting param of type '{$type}' to DateTime object"
        );
    }

    /**
     * @param mixed $date Anything that we can convert to a \DateTime object
     *
     * @return void
     */
    public function printISO8601Date($date)
    {
        echo $this->dateTimeFromAnything($date)->format('c');
    }

    /**
     * @param mixed $date Anything that we can convert to a \DateTime object
     */
    public function printRFC2822Date($date)
    {
        echo $this->dateTimeFromAnything($date)->format('r');
    }
}
  • 在涉及到接口输出的部分,使用ApiDoc的方式写代码注释
/**
 * @api {get} /user/:id Request User information
 * @apiName GetUser
 * @apiGroup User
 *
 * @apiParam {Number} id Users unique ID.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
  • apidoc和PHPDoc可以同时编写
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值