花点小精力修改你的项目规范
项目规范
从语言的说的话,我觉得 javascript
做得非常好。
最少权限原则
声明
原文: let vs. const
原文太长了,简单翻译下:
- 除了你要修改的变量都应该使用
const
- 用
const
,一看知道值不可能改变,推测数据的时候容易一点点。
同理,到了php
。
优先用: private
-> protected
-> public
。
如其名: 最少权限原则
布尔判断
$res = null;
$res === null // 好
$res == null // 一般
$res == 0 // 差
也就是(int)null == 0 拿语言特征乱玩
这里也有最少权限的味道
短路符代替if和else
$model->save() && $this->handleOrder();
$model->save() || error('保存失败') ;
很多情况都要一行 if
,用短路符代替挺香的。
别再for了 用常用函数
举例几个函数,项目肯定用到的。
因为 常用,基本每个语言都是一样用法和效果,
部分用js
代替。
only
bad:
$m = new Model();
$m->name = $request->name;
$m->unit = $request->unit;
$m->save();
good:
Model::create($request->only([
'name','unit'
]));
array_reduce
array_filter
array_map
代码写法规范工具
相比前端的eslint
普及性,php-cs-fixer
惨不忍睹。
手动配置 各种操作眼花缭乱 对英文不懂的,估计都不知道怎么配置
这成本…
(Hyperf 我感觉就很好,集成 php-cs-fixer
)
以Laravel9为例
composer require friendsofphp/php-cs-fixer --dev
// 安装 --dev代表开发依赖
根据自己项目创建规范
在项目跟目录创建文件 .php-cs-fixer.php
<?php
if (PHP_VERSION_ID <= 80001 || PHP_VERSION_ID >= 80100) {
fwrite(STDERR, '只支持php80');
exit(1);
}
$finder = PhpCsFixer\Finder::create()
->exclude('bootstrap') // 忽略这些文件夹
->exclude('public')
->exclude('storage')
->exclude('vendor')
->exclude('tests')
->in(__DIR__) // 项目根目录路径
;
// 改成你的php版本
$config = new PhpCsFixer\Config();
$config
->setRiskyAllowed(true)
->setRules([
'@PHP80Migration' => true,
'@PHP80Migration:risky' => true,
'@PHPUnit75Migration:risky' => true,
'@PhpCsFixer' => true,
'@PhpCsFixer:risky' => true,
'general_phpdoc_annotation_remove' => ['annotations' => ['expectedDeprecation']],
'modernize_strpos' => true, // needs PHP 8+ or polyfill
'heredoc_indentation' => true,
'declare_strict_types' => false,
])
->setFinder($finder)
->setUsingCache(false);
;
return $config;
运行
$a ='1';
$a==1;
./vendor/bin/php-cs-fixer fix
// window为: vendor/bin/php-cs-fixer fix
// 代码被修改为:
$a = '1';
1 === $a;
加入scripts
composer.json
的 scripts
"scripts": {
"cs-fix": "php-cs-fixer fix $1",
....
}
运行: composer cs-fix
model
条件查询
熟用orm
跟常用函数差不多,可以减少你大量的代码。
(虽然这是废话 但还是一堆用DB的)
Model 对应 表名
一堆Model
和 table name
整得很无语,一般我习惯sql
查数据的。
结果这个模型对应那个表名,我还必须得看模型的$table
。
请尽量别自定义table
了。
Model Fail
findOrfail 代替 find
firstOrFail 代替first
报错比数据错问题小得多。
生产环境
composer insatll --no-dev // 不安装开发环境的扩展包
opcache 开启
APP_DEBUG=false 关闭debug
本作品采用《CC 协议》,转载必须注明作者和本文链接
大佬都是随便写,没有规范,时间就是金钱,把钱花在刀刃上。
不太同意 “短路符代替 if 和 else” 这一点,其他的基本赞同。
(!$member) ? exit(json_encode(array('code' => -1, 'msg' => '尚未登录请登录'))) : false;
少写if/else就优雅?
以上代码看一次吐一次。