4

PHP程序员需要注意的代码规范PSR有哪些?

 1 year ago
source link: https://www.fly63.com/article/detial/12049
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

更新日期: 2022-08-25阅读: 12标签: 规范分享

扫一扫分享

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

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

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

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的变化

虽说现在已经8.0了,但还是很有必要看一下的。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。

630c186cc623d.jpg

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

链接: https://www.fly63.com/article/detial/12049


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK