hyperf-validate使用手册

Hyperf-Validate


基于hyperf/validation实现的validate层

安装


# -vvv显示composer 运行时详情
composer require death_satan/hyperf-validate -vvv

使用方式

通过命令生成一个 validate.我这里生成一个Demo


php bin/hyperf.php gen:validate Demo

执行后会在你的项目 app/validate目录下生成一个Demo验证器类

image

这里我修改为我需要的规则以及场景


<?php

declare(strict_types=1);
namespace App\Validate;

use DeathSatan\Hyperf\Validate\Lib\AbstractValidate as BaseValidate;

class Demo extends BaseValidate
{
    /**
    * @var array 自定义场景
    */
    protected $scenes =[
        'login'=>[
            'username','password'
        ], // 写一个login场景 在这个场景下校检username,password两个字段
        'reg'=>[
            'username',
        ],//写一个reg场景 在这个场景下只校检username字段
    ];

    /**
     * 自定义错误消息
     * @return array
     */
    protected function messages():array
    {
        return [
            'username.required'=>'昵称必须填写',
            'password.required'=>'密码必须填写'
        ];
    }

    /**
     * 自定义验证属性
     * @return array
     */
    protected function attributes():array
    {
        return [];
    }

    /**
     * 规则
     * @return array
     */
    protected function rules():array
    {
        return [
            'username'=>'required',
            'password'=>'required',
        ];
    }
}


在控制器中使用


<?php

declare(strict_types=1);

namespace App\Controller;

use App\Validate\Demo;
use DeathSatan\Hyperf\Validate\Exceptions\ValidateException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;

/**
 * @AutoController()
 */
class Index
{
    /**
     * @Inject
     * @var Demo
     */
    protected $validate;

    public function index(RequestInterface $request, ResponseInterface $response)
    {
        $data = $request->all();//取出来所有参数

        try {
		//通过scene方法指定场景,如果不使用场景则不调用即可
            $this->validate->scene('login')
                ->make($data);
        }catch (ValidateException $exception) //如果校检失败则会抛出ValidateException异常
        {
            return $response->json([
                'msg'=>$exception->getMessage(),//通过getMessage方法获取错误信息
            ]);
        }
        return $response->json([
            'msg'=>'success'
        ]);
    }
}

测试


image


image


image


在model中使用

新创建一个表

image

通过gen:model user生成model, 在model内使用注解标注


<?php

declare (strict_types=1);
namespace App\Model;

use DeathSatan\Hyperf\Validate\Annotation\ModelValidate;
use Hyperf\DbConnection\Model\Model;
/**
 * @property int $id 
 * @property string $username 
 * @property string $password
 * @ModelValidate(validate="\App\Validate\Demo",event="creating,updating,saving",scene="login")
 */
class User extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'user';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username','password'
    ];;
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer'];
}

在控制器内写入相关代码


<?php

declare(strict_types=1);

namespace App\Controller;

use App\Model\User;
use App\Validate\Demo;
use DeathSatan\Hyperf\Validate\Exceptions\ValidateException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use DeathSatan\Hyperf\Validate\Exceptions\ModelValidateException;

/**
 * @AutoController()
 */
class Index
{
    /**
     * @Inject
     * @var Demo
     */
    protected $validate;

    public function index(RequestInterface $request, ResponseInterface $response)
    {
        $data = $request->all();//取出来所有参数

        try {
            User::create($data);//直接使用create方法
        }catch (ModelValidateException $exception) //如果校检失败则会抛出ModelValidateException异常
        {
            return $response->json([
                'msg'=>$exception->getMessage(),//通过getMessage方法获取错误信息
            ]);
        }
        return $response->json([
            'msg'=>'success'
        ]);
    }
}

测试

image


image


image

查看数据表

image

ModelValidate注解参数详解

  • validate 必选 验证器类名
  • scene 非必选 场景选择
  • event 要在什么事件内进行数据校检 [非必选] 默认:creating,updating,saving
posted @ 2022-06-27 16:01  Death-Satan  阅读(672)  评论(0编辑  收藏  举报