PHP - code specification PSR

Posted by finkrattaz on Sat, 29 Jan 2022 03:25:42 +0100

summary

After carefully reviewing the writing specification of PHP code, I found that I do have many deficiencies and need to be improved. PHP code follows the PSR (PHP Standard Recommendation) specification. I forgot to read the book to psr4 before. Psr4 optimizes the dependency inversion of composer. Now it has been linked to psr18 and the official website php-fig .

The code is written casually, which seems unprofessional and inconvenient for others to read.

1. Variable and function writing hump (in my previous code, variables are underlined and humped, which is very nonstandard)

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

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

2. If it is only used by the current class and does not involve external class calls, the control permission is given to private, and the method name is underlined. If data is returned, it is better to keep the return data type unified.

private function _formatData($data)
{
     if(!$data) return [];
     
     foreach ($data as $val){
         //... slightly
     }
     
     return $data;
}

3.if conditions and nesting. if it's a personal habit, it's best to add {}. Some people are used to not adding it. There is no authoritative manual to say whether to add it or not.

function getPayAmount() {
  let result;
  if (isDead)
    result = deadAmount();
  else {
    if (isSeparated)
      result = separatedAmount();
    else {
      if (isRetired)
        result = retiredAmount();
      else
        result = normalPayAmount();
    }
  }
  return result;
}

After optimization, is it refreshing too much.

function getPayAmount() {
  if (isDead) return deadAmount();
  if (isSeparated) return separatedAmount();
  if (isRetired) return retiredAmount();
  return normalPayAmount();
}

4. Where it is repeated twice, write a function processing code. The advantage of writing the function processing code is that it can be modified uniformly during modification, which is convenient for calling, and has better performance. After the bottom calling function of PHP is completed, release the resources. If the code is not separated, wait for the execution of all programs to be released uniformly.

5. Chain call of ORM layer database. ORM mainly uses the idea of object-oriented to operate the database.

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

The following chain preprocesses Sql execution to prevent Sql injection:

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. Change from PHP5 to PHP7

The most important feature of PHP5 is to enrich the object-oriented design and syntax. The biggest feature of PHP7 is to improve the performance. Another small detail of PHP7 is that the weak type syntax is like the transformation style of strong type syntax, and the parameters are greatly limited.

My personal guess is that it may limit the data type, considering the improvement of performance, and there is a layer of type conversion at the bottom.

protected function onRequest(?string $action): ?bool
{
    //Receive parameters
    $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. The code column should be no more than 120, and the single function should be no more than 100 lines (psr2 original)

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. The theme of psr14 is Event Dispatcher, which is to write the defined object in the calling function.

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)
    {
        /** When the custom handshake rule returns false, the handshake is aborted */
        if (!$this->customHandShake($request, $response)) {
            $response->end();
            return false;
        }

        /** This is the WebSocket handshake verification process in the RFC specification. Otherwise, the handshake cannot be performed correctly */
        if ($this->secWebsocketAccept($request, $response)) {
            $response->end();
            return true;
        }

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

9. Code layering.

Just like the Tcp/Ip protocol, the complex processing process is to carry out artificial logical layering. The layering of PHP includes the previous MVC and the popular DDD mode. Some people say that MVC is a blood dripping mode. I personally think MVC is also very easy to use. We can't use whatever is popular on the Internet. The mainstream processing methods and modes are generally those of large companies, But how many large companies are there in the Internet? Developers should have their own way of thinking and use what to see the specific business needs.

10. There is another trick about PHPstrom setting and naming standard. If the naming is not standard, PHPstrom will prompt green wavy lines, and if the comments are not standard, PHPstrom will prompt yellow wavy lines. The following is an irregular Demo.

Mac format code: shift+alt+command+l