PHP编程基础篇1 - 代码规范PSR

概述

仔细的缕了一下关于PHP代码的书写规范,我发现我确实有很多不足的地方,需要改进,PHP代码遵循PSR(PHP Standard Recommendation)规范,之前忘了看那本书到psr4,psr4优化的是composer的依赖倒置,现在已经到psr18了,官网链接 php-fig

代码写的很随意,显得自己不专业,也给别人的阅读带来不便。

1.变量、函数写法驼峰(我之前的代码里就是变量有下划线、有驼峰非常不标准)

public function readMessage()
{
    $fdServer = new FdServer();
    $countServer = new CountServer();

    $toUid = $this->request->getToUid($this->body['to_uid']);
    $syncStamp = $this->request->getSyncStamp($this->body['syncstamp']);
    ##略
}

2.如果只是当前类使用,不涉及外面的类调用,控制权限给private,方法名用下划线,如果返回数据,返回数据类型最好也保持统一。

private function _formatData($data)
{
     if(!$data) return [];

     foreach ($data as $val){
         //...略
     }

     return $data;
}

3.if条件和嵌套,个人习惯如果是if最好是加上{},也有人习惯不加,没有权威手册说加好还是不加好。

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();
}

4.重复2次的地方,要写一个函数处理,写函数处理代码的好处是修改时可以统一修改,方便调用,而且在性能上也更优,PHP的底层调用函数结束后,释放资源,如果不分离代码,需等待全部程序执行完毕在统一释放。

5.ORM层数据库的链式调用,ORM主要是采用面向对象的思想对数据库进行操作。

Model::create()->where('status', 1)->where(' (id > 10 or id <2) ')->get();

底下的链式对Sql执行进行了预处理,防止Sql注入:

public function getNovelApplyCount(int $nid)
{
    $sql = "SELECT COUNT(*) number FROM {$this->table}
            WHERE `novel_id` = :novel_id";
    $data = [
        ':novel_id' => $nid,
    ];

    $tag = $this->getNovelTag($nid);
    $res = $this->dao->conn(false)->setTag($tag)->preparedSql($sql, $data)->fetchOne();
    return $res['number'] ?? 0;
}

6.PHP5到PHP7的变化

PHP5最重要的特性就是丰富了面向对象的设计和语法,PHP7最大的特性就是提升了性能,PHP7还有个小细节是弱类型语法像强类型语法转变的风格,参数做了很大的限制。

我个人猜想可能是限制了数据类型,考虑的是性能的提升,底层少了一层类型转化。

protected function onRequest(?string $action): ?bool
{
    //接收参数
    $this->params = $this->request()->getRequestParam();
    $this->method = $this->request()->getMethod();
    return true;
}

private static function _formatQueryData(string $loginKey): string
{
    $data['timestamp'] = time();
    $data['loginKey'] = $loginKey;
    $token = self::setToken($data);
    $data['token'] = $token;
    $params = http_build_query($data);
    return $params;
}

7.代码列 最好不要超过 120,单个函数 不要超过 100 行(psr2原文)

There MUST NOT be a hard limit on line length.

The soft limit on line length MUST be 120 characters; automated style checkers MUST warn but MUST NOT error at the soft limit.

Lines SHOULD NOT be longer than 80 characters; lines longer than that SHOULD be split into multiple subsequent lines of no more than 80 characters each.

There MUST NOT be trailing whitespace at the end of non-blank lines.

Blank lines MAY be added to improve readability and to indicate related blocks of code.

There MUST NOT be more than one statement per line.

8.psr14的主题是Event Dispatcher,大概就是把定义的对象写在调用函数里。

class WebSocketEvent
{
    const MYSQL_CONN_NAME = 'mysql-msg';
    /**
     * @param \Swoole\Http\Request $request
     * @param \Swoole\Http\Response $response
     * @return bool
     */
    public function onHandShake(\Swoole\Http\Request $request, \Swoole\Http\Response $response)
    {
        /** 此处自定义握手规则 返回 false 时中止握手 */
        if (!$this->customHandShake($request, $response)) {
            $response->end();
            return false;
        }

        /** 此处是  RFC规范中的WebSocket握手验证过程 必须执行 否则无法正确握手 */
        if ($this->secWebsocketAccept($request, $response)) {
            $response->end();
            return true;
        }

        $response->end();
        return false;
    }
}

9.代码分层。

就像Tcp/Ip协议一样,复杂的处理过程就是进行人为的逻辑分层,PHP的分层有之前的MVC和现在流行的DDD模式,有人说MVC是滴血模式,我个人觉得MVC也是很好用的,不能网上流行什么我们就用什么,主流的一般都是大公司的处理方式和模式,可是互联网一共有多少大公司呢,开发者要有自己的思维方式,用什么看具体的业务需要。

10.PHPstrom的设置,命名规范还有个小窍门,如果是命名不规范,PHPstrom会提示绿色波浪线,注释不规范就会提示黄色波浪线,下面是不规则的Demo。

Mac格式化代码:shift+alt+command+l

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!