Files
rxthinkcmf-wiki/RXThinkCMF_Laravel13_NaiveVue/zh/standards/backend-code.md
T
2026-10-08 17:50:29 +08:00

135 lines
3.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 12.6 后端编码规范
:::tip 概述
本节定义后端 PHP 代码的编写规范,包括 Model、Service、Controller、FormRequest 各层的命名和结构规范,确保团队代码风格统一。代码风格以 Laravel Pint(`./vendor/bin/pint`)为准。
:::
## Model 层规范
```php
// 继承 Eloquent Model(app/Models/Example.php)
class Example extends Model
{
// 软删除(is_delete)+ 审计字段(create_user/create_time/update_user/update_time)
use HasAuditColumns, SoftDeletesByFlag;
/**
* 对应数据库表名
*
* @var string
*/
protected $table = 'example';
/**
* 批量赋值白名单
*
* @var array<int, string>
*/
protected $fillable = ['name', 'avatar', 'type', 'status', 'sort'];
}
```
## Service 层规范
```php
// 系统共享模块继承 BaseService
class ExampleService extends BaseService
{
use HasCrudOperations, HasQueryScopes, HasSerializeMaps;
/**
* 关联的模型类
*
* @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;
}
}
// 租户模块继承 BaseTenantService(含 tenant_id 的业务表)
class UserService extends BaseTenantService { ... }
```
可用生命周期钩子(`HasCrudOperations`):`beforeAdd` / `afterAdd` / `beforeUpdate` / `afterUpdate` / `beforeDelete` / `afterDelete` / `beforeBatchDelete` / `afterBatchDelete` / `afterDetail` / `afterPageList`。
## Controller 层规范
```php
class ExampleController extends Controller
{
// 构造函数注入 Service(不在 initialize 中手动 new)
public function __construct(protected ExampleService $exampleService) {}
// 使用注解
#[OperationLog('示例管理-新增', OperationLog::TYPE_ADD)]
#[Permission('sys:example:add', '新增示例')]
public function add(ExampleRequest $request): JsonResponse
{
return $this->_add($this->exampleService, $request->validated());
}
}
```
:::tip 瘦控制器
Controller 只做三件事:参数获取(FormRequest)→ 调用 Service → 返回 JSON。业务规则一律写在 Service,不在控制器写 if/else 业务判断。
:::
## FormRequest 层规范
```php
class ExampleRequest extends BaseRequest
{
public function rules(): array
{
return [
'name' => 'required|string|max:255', // ✅ 驼峰命名
'categoryId' => 'required|integer', // ✅ 驼峰命名
// 'category_id' => 'required', // ❌ 禁止下划线
];
}
public function messages(): array
{
return [
'name.required' => '名称不能为空',
'categoryId.required' => '分类不能为空',
];
}
}
```
:::warning 字段名必须使用驼峰
FormRequest 中的字段名必须使用 camelCase(驼峰),与前端传参一致——使用下划线会导致校验规则匹配不到字段。控制器以 `validated()` 取数原样传递,键名转换由 Service 写入入口(doAdd/doUpdate)统一完成。
:::
## 注解规范
- 所有写操作(POST/PUT/DELETE)必须标注 `#[OperationLog('模块-操作', OperationLog::TYPE_XXX)]`
- 所有需要权限控制的接口必须标注 `#[Permission]`
- 权限码格式:`sys:{模块名}:{操作}`
- 演示环境放行的只读接口标注 `#[DemoAllow]`