从laravel转到webman发现表单验证不能使用依赖注入自动验证所以改造了一下。
1、创建一个BaseValidate基类,基类继承app\validate,校验类继承基类
2、在基类的构造方法里调用check方法,这样在依赖注入的时候就会自动进行校验,校验失败抛出异常
3、在异常处理类中接住,并自定义响应
<?php
declare (strict_types=1);
namespace app\validate;
use think\Validate;
class BaseValidate extends Validate
{
public function __construct() {
if ($this->scene){
$scene = request()->action;
if (!$this->hasScene($scene)){
return;
}
$this->scene($scene);
}
$this->failException()->check(request()->all());
}
}
<?php
declare (strict_types=1);
namespace app\validate;
use app\validate\BaseValidate;
class TestValidate extends BaseValidate
{
protected $rule = [
'name' => 'require',
'age' => 'require',
];
protected $message = [
'name.require' => '名称必须',
'age.require' => '年龄必须',
];
protected $scene = [
'edit' => ['name'],
'del' => ['age'],
];
}
<?php
/**
* This file is part of webman.
*
* Licensed under The MIT License
* For full copyright and license information, please see the MIT-LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @author walkor<walkor@workerman.net>
* @copyright walkor<walkor@workerman.net>
* @link http://www.workerman.net/
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace support\exception;
use think\exception\ValidateException;
use Throwable;
use Webman\Exception\ExceptionHandler;
use Webman\Http\Request;
use Webman\Http\Response;
/**
* Class Handler
* @package support\exception
*/
class Handler extends ExceptionHandler
{
public $dontReport = [
BusinessException::class,
];
public function report(Throwable $exception)
{
parent::report($exception);
}
public function render(Request $request, Throwable $exception): Response
{
if ($exception instanceof ValidateException) {
return json([
'code' => 500,
'msg' => $exception->getMessage(),
'data' => null
]);
}
if(($exception instanceof BusinessException) && ($response = $exception->render($request)))
{
return $response;
}
return parent::render($request, $exception);
}
}
<?php
namespace app\controller;
use app\validate\TestValidate;
class IndexController
{
public function edit(TestValidate $validate)
{
return 'edit';
}
public function del(TestValidate $validate)
{
return 'del';
}
}
<?php
namespace app\controller;
use app\validate\TestValidate;
class IndexController
{
public function __construct()
{
new TestValidate();
}
public function index()
{
return 'index';
}
public function edit()
{
return 'edit';
}
public function del()
{
return 'del';
}
}