签入版本
This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
# 12.6 后端编码规范
|
||||
|
||||
:::tip 概述
|
||||
本节定义后端 PHP 代码的编写规范,包括 Model、Logic、Controller、Validate 各层的命名和结构规范,确保团队代码风格统一。
|
||||
:::
|
||||
|
||||
## Model 层规范
|
||||
|
||||
```php
|
||||
// 继承 BaseModel
|
||||
class Example extends BaseModel
|
||||
{
|
||||
/**
|
||||
* 对应数据库表名(不含前缀)
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $name = 'example';
|
||||
}
|
||||
```
|
||||
|
||||
## Logic 层规范
|
||||
|
||||
```php
|
||||
// 系统共享模块继承 BaseLogic
|
||||
class ExampleLogic extends BaseLogic
|
||||
{
|
||||
/**
|
||||
* 关联的模型类
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected string $modelClass = Example::class;
|
||||
|
||||
/**
|
||||
* LIKE 模糊匹配字段
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected array $pageLikeFields = ['name'];
|
||||
|
||||
/**
|
||||
* 精确匹配字段
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected array $pageEqFields = ['status'];
|
||||
|
||||
/**
|
||||
* 新增前处理
|
||||
*
|
||||
* @param array $data 待新增的数据
|
||||
* @return array 处理后的数据
|
||||
*/
|
||||
protected function beforeAdd(array $data): array
|
||||
{
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
|
||||
// 租户模块继承 BaseTenantLogic
|
||||
class UserLogic extends BaseTenantLogic { ... }
|
||||
```
|
||||
|
||||
## Controller 层规范
|
||||
|
||||
```php
|
||||
class ExampleController extends BaseController
|
||||
{
|
||||
protected ExampleLogic $logic;
|
||||
|
||||
protected function initialize(): void
|
||||
{
|
||||
$this->logic = new ExampleLogic();
|
||||
}
|
||||
|
||||
// 使用注解
|
||||
#[Log('模块-操作', Log::TYPE_ADD)]
|
||||
#[Permission('sys:example:add', '添加')]
|
||||
public function add(): Json
|
||||
{
|
||||
return parent::_add($this->logic, $this->getJsonBody());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Validate 层规范
|
||||
|
||||
```php
|
||||
class ExampleValidate extends Validate
|
||||
{
|
||||
protected $rule = [
|
||||
'name' => 'require',
|
||||
'categoryId' => 'require', // ✅ 驼峰命名
|
||||
// 'category_id' => 'require', // ❌ 禁止下划线
|
||||
];
|
||||
|
||||
protected $message = [
|
||||
'name.require' => '名称不能为空',
|
||||
'categoryId.require' => '分类不能为空',
|
||||
];
|
||||
|
||||
protected $scene = [
|
||||
'add' => ['name', 'categoryId'],
|
||||
'update' => ['name'],
|
||||
];
|
||||
}
|
||||
```
|
||||
|
||||
:::warning 字段名必须使用驼峰
|
||||
Validate 中的字段名必须使用 camelCase(驼峰),与前端传参一致。
|
||||
因为校验发生在 `BaseLogic::beforeAdd` 之后、`array_camel_to_snake` 转换之前,
|
||||
此时数据键名还是驼峰形式。使用下划线会导致校验规则匹配不到字段。
|
||||
:::
|
||||
|
||||
## 注解规范
|
||||
|
||||
- 所有写操作(POST/PUT/DELETE)必须标注 `#[Log]`
|
||||
- 所有需要权限控制的接口必须标注 `#[Permission]`
|
||||
- 权限码格式:`sys:{模块名}:{操作}`
|
||||
Reference in New Issue
Block a user