控制器Controller的作用定义路由、中间件和校验提交的数据。一些比较简单的业务处理逻辑都也可能会在Controller写,但是如果有比较稍微复杂的业务逻辑,都建议封装到Service中
一、创建控制器
通过 hcms 命令 创建控制php bin/hyperf.php hcms:controller question test
。执行后,系统会在指定模块下创建控制,并自动生成路由注解和一个默认的index
方法。
<?php
declare(strict_types=1);
namespace App\Application\Question\Controller;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
/**
* @Controller(prefix="/question/test")
*/
class TestController extends AbstractController
{
/**
* @GetMapping(path="index")
*/
public function index()
{
return "hello question/test1 index";
}
}
二、路由
管理后台由我们都推荐使用 Hyperf\HttpServer\Annotation\Controller
的注解进行定义,这样方便灵活对路由进行定义和对所需校验的权限进行分类。
使用 Controller
注解就需要在每一个方法具体的路由方法使用 PostMapping 或 GetMapping。
路由规范:{$module_name}/{$controller}/{$action}
- module_name:对应模块名称
- controller:对应控制器名称
action:对应操作名称,同页面多个操作可以使用对层级路由,例如
index
和index/delete
。/** * @Middleware(AdminMiddleware::class) * @Controller(prefix="admin/user") */ class UserController extends AbstractController{ /** * @PostMapping(path="delete") */ function delete() { } }
三、返回
视图
注解
App\Annotation\View
。视图都是通过View注解在App\Aspect\ViewAspect
切片中实现。/** * @View() * @GetMapping(path="index") */ function index() { } //或 /** * @View() * @GetMapping(path="index") */ public function index() { return RenderParam::display(); }
渲染路径
$template = "{$module_name}/View/{$controller}/{$template}";
$module_name:模块名称,例Admin
$controller:控制器名称
$template:对应模板名称,默认是控制器的方法名
Api
注解 App\Annotation\Api
是用于规定json返回的,有了API注解可以ApiAspect接管返回,对于正确的返回就不需要重复的写 $this->returnSuccessJson()
。
/**
* 直接返回数组,默认成功方式
* @Api()
* @GetMapping(path="lists")
*/
public function lists()
{
return [];
}
/**
* 返回成功json
* @Api()
* @GetMapping(path="lists")
*/
public function lists()
{
return $this->returnSuccessJson();
}
管理后台页面都涉及到的接口调用,统一都使用 returnSuccessJson
和returnErrorJson
返回成功和失败的数据格式。
returnSuccessJson
- data 返回数据 默认array ,这里是数组,不要直接将数据库的model返回
- msg 返回结果信息,成功默认请求成功或操作成功
- code 成功默认是200
-
returnErrorJson
msg 返回结果消息,只要是错误这些第一个必填的信息
- code 默认错误是500
- data 错误更多数据信息
- status 错误默认是false
四、数据验证
hyperf 官网文档
官网上有很多使用方式,这里推荐直接在Controller定义验证,如果有更复杂或者其他需求,可以查看文档做更完善的校验定义。
<?php
declare(strict_types=1);
namespace App\Application\Admin\Controller;
use App\Application\Admin\Middleware\AdminMiddleware;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Controller\AbstractController;
/**
* @Middleware(AdminMiddleware::class)
* @Controller(prefix="admin/user")
*/
class UserController extends AbstractController
{
function submitEdit()
{
$validator = $this->validationFactory->make($this->request->all(), [
'role_id' => 'required',
'real_name' => 'required',
'username' => 'required',
], [
'role_id.required' => '请选择所属的角色',
'real_name.required' => '请输入管理员姓名',
'username.required' => '请输入登录用户名',
]);
if ($validator->fails()) {
return $this->returnErrorJson($validator->errors()
->first());
}
//……
}
}