laravel-controller-cleanup
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseController Cleanup
控制器优化
Keep controllers small and focused on orchestration.
保持控制器代码精简,专注于编排逻辑。
Move auth/validation to Form Requests
将权限验证/校验逻辑移至Form Requests
- Create a Request class (e.g., ) and use
StoreUserRequest+authorize()rules() - Type-hint the Request in your controller method; Laravel runs it before the action
php artisan make:request StoreUserRequest- 创建一个Request类(例如),并实现
StoreUserRequest+authorize()方法rules() - 在你的控制器方法中对该Request进行类型提示;Laravel会在执行动作前自动运行验证逻辑
php artisan make:request StoreUserRequestExtract business logic to Actions/Services
将业务逻辑抽离到Actions/Services中
- Create a small Action (one thing well) or a Service for larger workflows
- Pass a DTO from the Request to the Action to avoid leaking framework concerns
php
final class CreateUserAction {
public function __invoke(CreateUserDTO $dto): User { /* ... */ }
}- 为单一职责的逻辑创建轻量Action,为更复杂的工作流创建Service
- 将Request中的DTO传递给Action,避免泄露框架相关的逻辑耦合
php
final class CreateUserAction {
public function __invoke(CreateUserDTO $dto): User { /* ... */ }
}Prefer Resource or Single-Action Controllers
优先使用资源控制器或单动作控制器
- Use resource controllers for standard CRUD
- For one-off endpoints, use invokable (single-action) controllers
- 对标准CRUD场景使用资源控制器
- 对于一次性的端点,使用可调用(单动作)控制器
Testing
测试相关
- Write feature tests for the controller route
- Unit test Actions/Services independently with DTOs
- 为控制器路由编写功能测试
- 结合DTO对Actions/Services独立编写单元测试