解决接口用map接收客户端参数的方案
引出问题,代码如下:
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Services\RegisterService;
use Hyperf\Context\ApplicationContext;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class IndexController extends AbstractController
{
/**
* 注册用户
* @return array
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function index(): array
{
$data = $this->request->all();
$validator = ApplicationContext::getContainer()->get(ValidatorFactoryInterface::class)->make(
$data,
[
'account' => 'required|string',
'password' => 'required|string',
'verification_code' => 'required|string',
],
);
if ($validator->fails()) {
return [
'code' => 1,
'message' => $validator->getMessageBag()->first(),
];
}
$data = $validator->validated();
return [
'code' => 0,
//create方法接收一个data,data里面有什么东西,编辑器是不知道的
'data' => RegisterService::create($data),
'message' => '注册成功',
];
}
}
上面的代码中RegisterService::create
的入参是一个map,里面有什么东西,编辑器无法识别。
我解决方案是,用一个类去描述需要的参数,类的成员属性的校验规则用注解进行描述。
上的代码,可以写成:
<?php
namespace App\Arg;
use Arg\Attr\ArgValidationAttr;
use Arg\BaseArgForHyperf;
/**
* 注册一个用户
*/
class RegisterArg extends BaseArgForHyperf
{
/**
* @var string 账号
*/
#[ArgValidationAttr('required')]
public string $account;
/**
* @var string 密码
*/
#[ArgValidationAttr('required')]
public string $password;
/**
* @var string 验证码
*/
#[ArgValidationAttr('required')]
public string $verification_code;
}
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Arg\RegisterArg;
use App\Services\RegisterService;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class IndexController extends AbstractController
{
/**
* 注册用户
* @return array
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function index(): array
{
//初始化参数类
$registerArg = new RegisterArg($this->request->all());
//校验数据
$msgBag = $registerArg->validate();
if ($msgBag->isNotEmpty()) {
//校验失败,返回错误信息
return [
'code' => 1,
'message' => $msgBag->first(),
];
}
//调用service层的注册逻辑,执行注册动作,并返回注册结果
return [
'code' => 0,
'data' => RegisterService::create($registerArg),
'message' => '注册成功',
];
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: