# 验证器
# 前言
herosphp/validate (opens new window) 衍生于 topthink/think-validate (opens new window),我们对它进行了一些改造,但保持了大部分验证规则的相同。在这里感谢一下topthink (opens new window) 开发组,实现了如此强大好用的验证器组件。
# 安装
# 1. 安装扩展
composer require herosphp/validate
# 2. 新建中间件
您需要为使用到验证器组件,在全局的中间件 /config/middleware.config.php
配置文件加上一个全局中间件 app\middleware\ValidateMiddleware
的配置。
<?php
declare(strict_types=1);
use app\middleware\ValidateMiddleware;
return [
ValidateMiddleware::class
];
app\middleware\ValidateMiddleware.php
<?php
namespace app\middleware;
use herosphp\core\HttpRequest;
use herosphp\core\MiddlewareInterface;
use herosphp\plugin\validate\Valid;
use herosphp\plugin\validate\Validate;
use herosphp\plugin\validate\ValidateException;
use herosphp\WebApp;
class ValidateMiddleware implements MiddlewareInterface
{
/**
* @throws \ReflectionException
*/
public function process(HttpRequest $request, callable $handler)
{
$reflectionMethod = new \ReflectionMethod(WebApp::$_targetController, WebApp::$_targetMethod);
$reflectionAttributes = $reflectionMethod->getAttributes(Valid::class);
if ($reflectionAttributes) {
foreach ($reflectionAttributes as $validAttribute) {
/** @var Valid $methodValidInstance */
$methodValidInstance = $validAttribute->newInstance();
$methodVInstance = new ($methodValidInstance->class);
if (!$methodVInstance instanceof Validate) {
throw new ValidateException("{$methodVInstance->class} must extend \\herosphp\\plugin\\validate\Validate");
}
$methodVInstance->scene($methodValidInstance->scene)->check([...$request->get(), ...$request->post()]);
}
}
return $handler($request);
}
}
在验证器验证失败时候,中间件会抛出一个herosphp\plugin\validate\ValidateException
的异常。
异常处理
框架为我们提供了一个全局异常处理器 app\exception\ExceptionHandler
捕获各种异常,您需要手动将这个异常在Handler捕获,也可以自定义您的异常返回结果。
# 使用
前面已经正确安装了,后续我们举个栗子说明怎么用。话不多说,show code。
如没有正确设置全局中间件,可能会导致验证器的使用方式无效。
# 1. 验证器文件
<?php
declare(strict_types=1);
namespace app\validate;
use herosphp\plugin\validate\Validate;
class MpValidate extends Validate
{
protected array $rule = [
'appId' => 'require',
'secret' => 'require',
'path' => 'require',
];
protected array $message = [
'appId.require' => '请填写小程序APPID',
'secret.require' => '请填写小程序SECRET',
'path.require' => '请选择客户名称',
];
protected array $scene = [
'add' => ['appId', 'secret', 'path'],
'create' => ['appId', 'secret'],
];
}
# 2. 控制器
验证器需在模板的控制器方法上,使用验证器注解Valid
。
#[Post(uri: '/mp/url', desc: '生成链接')]
#[Valid(class: MpValidate::class, scene: 'add')]
public function post(): HttpResponse
{
/** @var UrlVo $vo */
$vo = GF::params2vo(UrlVo::class);
WechatUrl::shortUrl($vo->getAppId(), $vo->getSecret(), $vo->getPath());
$url = Url::create([
'id' => StringUtil::genGlobalUid(),
'appid' => $vo->getAppId(),
'secret' => $vo->getSecret(),
'path' => $vo->getPath(),
]);
return Result::ok()->data(['url' => GF::getAppConfig('domain') . '/mp/' . $url->id]);
}
# 规则
组件衍生于 ThinkPHP Validate (opens new window),相关操作均可参考 ThinkPHP Validate 的文档。