控制器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";
}
}
通过命令、或者手动创建控制器之后,可能会出现找不到路由的情况。可能是因为扫描缓存的问题,如果你是开发状态,建议在 .env
文件 增加 SCAN_CACHEABLE=false
配置。修改配置后再执行重启命令,还有在本地开发环境建议使用 composer watch
启动,因为这样有文件变动会重启服务。
管理后台由我们都推荐使用 Hyperf\HttpServer\Annotation\Controller
的注解进行定义,这样方便灵活对路由进行定义和对所需校验的权限进行分类。
使用 Controller
注解就需要在每一个方法具体的路由方法使用 PostMapping 或 GetMapping。
路由规范:{$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]
function index() { }
//或
#[View]
#[GetMapping]
public function index()
{
return RenderParam::display();
}
$template = "{$module_name}/View/{$controller}/{$template}";
$module_name:模块名称,例Admin
$controller:控制器名称
$template:对应模板名称,默认是控制器的方法名
注解 App\Annotation\Api
是用于规定json返回的,有了API注解可以ApiAspect接管返回,对于正确的返回就不需要重复的写 $this->returnSuccessJson()
。
/**
* 直接返回数组,默认成功方式
*/
#[Api]
#[GetMapping]
public function lists()
{
return [];
}
/**
* 返回成功json
*/
#[Api]
#[GetMapping]
public function lists()
{
return $this->returnSuccessJson();
}
管理后台页面都涉及到的接口调用,统一都使用 returnSuccessJson
和returnErrorJson
返回成功和失败的数据格式。
官网上有很多使用方式,这里推荐直接在Controller定义验证,如果有更复杂或者其他需求,可以查看文档做更完善的校验定义。
推荐使用:参数接收与验证 RequestParam
<?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());
}
//……
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。