Laravel 验证器多场景封装与使用指南
前言
在使用 Laravel 框架进行数据验证时,开发者通常依赖 Illuminate\Http\Request 对象的 validate 方法,或者使用 FormRequest 类和 Validator 类来处理表单数据的合法性检查。
FormRequest 能够将验证逻辑从控制器中分离,避免控制器代码过于庞大。当验证失败时,它会自动生成重定向响应并将用户送回上一页,同时将错误信息闪存到 Session 中以供页面展示。对于 AJAX 或 API 请求,它会返回状态码为 422 的 JSON 格式错误数据。若需定制返回的 JSON 结构,则需额外处理。
在实际开发中,一个业务模块往往对应多种验证场景。如果为每个场景都创建一个独立的 FormRequest 文件,会导致项目结构繁琐且冗余。因此,通过在一个验证类中适配多个场景,可以显著提升开发效率。
开始
首先,我们封装了一个名为 BaseValidate.php 的基类,并将其放置在 app\Validate 目录下。当然,该文件也可以存放在其他位置,只需确保命名空间配置正确即可。
<?php
namespace App\Validate;
use Illuminate\Support\Facades\Validator;
/**
* 扩展验证器
*/
class BaseValidate {
/**
* 当前验证规则
* @var array
*/
protected $rule = [];
/**
* 验证提示信息
* @var array
*/
protected $message = [];
/**
* 验证场景定义
* @var array
*/
protected $scene = [];
/**
* 设置当前验证场景
* @var array
*/
protected $currentScene = null;
/**
* 验证失败错误信息
* @var array
*/
protected $error = [];
/**
* 场景需要验证的规则
* @var array
*/
protected $only = [];
/**
* 设置验证场景
* @access public
* @param string $name 场景名
* @return $this
*/
public function scene($name)
{
// 设置当前场景
$this->currentScene = $name;
return $this;
}
/**
* 数据验证
* @access public
* @param array $data 数据
* @param mixed $rules 验证规则
* @param array $message 自定义验证信息
* @param string $scene 验证场景
* @return bool
*/
public function check($data, $rules = [], $message = [],$scene = '')
{
$this->error =[];
if (empty($rules)) {
//读取验证规则
$rules = $this->rule;
}
if (empty($message)) {
$message = $this->message;
}
//读取场景
if (!$this->getScene($scene)) {
return false;
}
//如果场景需要验证的规则不为空
if (!empty($this->only)) {
$new_rules = [];
foreach ($this->only as $key => $value) {
if (array_key_exists($value,$rules)) {
$new_rules[$value] = $rules[$value];
}
}
$rules = $new_rules;
}
// var_dump($rules);die;
$validator = Validator::make($data,$rules,$message);
//验证失败
if ($validator->fails()) {
$this->error = $validator->errors()->first();
return false;
}
return !empty($this->error) ? false : true;
}
/**
* 获取数据验证的场景
* @access protected
* @param string $scene 验证场景
* @return void
*/
protected function getScene($scene = '')
{
if (empty($scene)) {
// 读取指定场景
$scene = $this->currentScene;
}
$this->only = [];
if (empty($scene)) {
return true;
}
if (!isset($this->scene[$scene])) {
//指定场景未找到写入error
$this->error = "scene:".$scene.'is not found';
return false;
}
// 如果设置了验证适用场景
$scene = $this->scene[$scene];
if (is_string($scene)) {
$scene = explode(',', $scene);
}
//将场景需要验证的字段填充入only
$this->only = $scene;
return true;
}
// 获取错误信息
public function getError()
{
return $this->error;
}
}
使用
接下来以文章提交信息的验证为例。我们需要新建一个文章验证类 ArticleValidate.php,并在其中填充相应的验证逻辑内容。
<?php
namespace App\Validate;
use App\Validate\BaseValidate;
/**
* 文章验证器
*/
class ArticleValidate extends BaseValidate {
//验证规则
protected $rule =[
'id'=>'required',
'title' => 'required|max:255',
'content' => 'required',
];
//自定义验证信息
protected $message = [
'id.required'=>'缺少文章id',
'title.required'=>'请输入title',
'title.max'=>'title长度不能大于 255',
'content.required'=>'请输入内容',
];
//自定义场景
protected $scene = [
'add'=>"title,content",
'edit'=> ['id','title','content'],
];
}
在该类中,主要定义了三个核心属性:用于指定验证规则的 rule、用于自定义错误提示的 message,以及用于区分不同验证流程的 scene。
非场景验证
对于不需要区分场景的基础验证,只需直接定义好验证规则即可。
public function update(){
$ArticleValidate = new ArticleValidate;
$request_data = [
'id'=>'1',
'title'=>'我是文章的标题',
'content'=>'我是文章的内容',
];
if (!$ArticleValidate->check($request_data)) {
var_dump($ArticleValidate->getError());
}
}
check 方法包含四个参数:第一个为待验证的数据数组,第二个为验证规则,第三个为自定义错误信息,第四个为验证场景。其中后三个参数为非必填项。若验证未通过,可调用 getError() 方法获取错误信息,但需注意该方法目前暂不支持一次性返回所有验证错误。
场景验证
若需启用场景验证功能,必须先在验证类中预先定义好各个场景的具体内容。
场景定义支持字符串或数组格式。当使用字符串时,多个字段之间需用逗号隔开;使用数组时则更为直观。
//自定义场景
protected $scene = [
'add'=>"title,content",
'edit'=> ['id','title','content'],
];
定义好场景后,即可在控制器的业务逻辑中进行具体的数据验证操作。
public function add(){
$ArticleValidate = new ArticleValidate;
$request_data = [
'title'=>'我是文章的标题',
'content'=>'我是文章的内容',
];
if (!$ArticleValidate->scene('add')->check($request_data)) {
var_dump($ArticleValidate->getError());
}
}
控制器内验证
此外,开发者也可以选择不创建专门的验证类,而是直接基于基类进行即时验证。
public function add(){
$Validate = new BaseValidate;
$request_data = [
'title'=>'我是文章的标题',
'content'=>'我是文章的内容',
];
$rule =[
'id'=>'required',
'title' => 'required|max:255',
'content' => 'required',
];
//自定义验证信息
$message = [
'id.required'=>'缺少文章id',
'title.required'=>'请输入title',
'title.max'=>'title长度不能大于 255',
'content.required'=>'请输入内容',
];
if (!$Validate->check($request_data,$rule,$message)) {
var_dump($Validate->getError());
}
}
通过引入验证场景机制,不仅有效减少了控制器内的代码量,还避免了因场景增多而导致 FormRequest 文件泛滥的问题。同时,这种设计使得自定义 JSON 返回格式变得更加便捷。
参考文档
laravel 表单验证 :表单验证《Laravel 5.5 中文文档》 thinkphp 验证场景 :https://www.kancloud.cn/manual/thinkphp5_1/354104
到此这篇关于为你的 Laravel 验证器加上多验证场景的实现的文章就介绍到这了,更多相关Laravel 验证器内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
本文为杨攀遥原创文章,如若转载,无需和我联系,但请注明出处 [杨攀遥的博客]:https://www.yangpanyao.com/archives/120.html