hyperf 验证 trait | php 技术论坛-大发黄金版app下载
模仿laravel
的validatesrequest
写的一个trait,仅供参考。
trait
类:
getvalidationfactory()->make($request->all(), $validator);
}
return $validator->validate();
}
/**
* @param requestinterface $request
* @param array $rules
* @param array $messages
* @param array $customattributes
* @return mixed
*
* @throws validationexception
*/
public function validate(requestinterface $request, array $rules,
array $messages = [], array $customattributes = [])
{
return $this->getvalidationfactory()->make(
$request->all(), $rules, $messages, $customattributes
)->validate();
}
/**
* @param $errorbag
* @param requestinterface $request
* @param array $rules
* @param array $messages
* @param array $customattributes
* @return mixed
*
* @throws validationexception
*/
public function validatewithbag($errorbag, requestinterface $request, array $rules,
array $messages = [], array $customattributes = [])
{
try {
return $this->validate($request, $rules, $messages, $customattributes);
} catch (validationexception $e) {
$e->errorbag = $errorbag;
throw $e;
}
}
/**
* @return validatorfactoryinterface
*/
protected function getvalidationfactory()
{
return make(validatorfactoryinterface::class);
}
}
用法:
在 abstractcontroller
中
use validatesrequests;
然后就可以在继承abstractcontroller
所有的控制器中这样使用了:
public function index(requestinterface $request)
{
$this->validate($request, [
'id' => 'required|integer'
], [], [
'id' => 'id',
]);
}
异常类
定义一个异常类来catch
到验证异常
stoppropagation();
/** @var \hyperf\validation\validationexception $throwable */
$body = json_encode([
'errors' => $throwable->validator->errors()->first()
], json_unescaped_unicode);
return $response->withheader('content-type', 'application/json')->withstatus($throwable->status)->withbody(new swoolestream($body));
}
public function isvalid(throwable $throwable): bool
{
return $throwable instanceof \hyperf\validation\validationexception;
}
}
然后在config/autoload/exceptions.php
中添加
return [
'handler' => [
'http' => [
app\exception\handler\systemexceptionhandler::class,
app\exception\validationexception::class, //该处就是验证异常类 必须放在appexceptionhandler上
app\exception\handler\appexceptionhandler::class,
],
],
];
本作品采用《cc 协议》,转载必须注明作者和本文链接
: 1: