php8.0+ 注解,反射表单验证

创建BaseRequest 继承 FormRequest 并重写createDefaultValidator方法

<?php
namespace App\Requests;

use Illuminate\Contracts\Validation\Factory;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
class BaseRequest extend FormRequest
{
    /**
     * 验证失败
      * @param Validator $validator
      * @return mixed
     */protected function failedValidation(Validator $validator): mixed
     {
            $error = $validator->errors()->all();
            throw new HttpResponseException(response()->json(['code' => -1,'message' => $error[0]]));
    }
    /**
     * 表单注解验证 v8.0 +
     * @param Factory $factory
     * @return Validator
     */
    public function createDefaultValidator(Factory $factory): Validator
    {
        $data  = $this->input();
        $rules = [];
        $class = new \ReflectionClass($this);
        $properties = $class->getProperties();
        foreach ($properties as $property) {
            $attribute = $property->getAttributes()[0] ?? [];
            if (empty($attribute)) {
                continue;
            }
            if (! str_ends_with($attribute->getName(), 'Param')) {
                continue;
            }
            // 这是需要注入的表单验证属性
            $arguments = $attribute->getArguments();
            $key = $arguments['name'];
            $rules[$key] = $arguments['rules'];
        }
        // 合并
        $rules      = array_merge($this->rules(), $rules);
        $messages   = array_merge($this->messages(), []);
        $attributes = array_merge($this->attributes(), []);
        return $factory->make($data, $rules, $messages, $attributes);
    }
}

创建自定义注解类

<?php
namespace App\Annotation;
use Attribute;

#[Attribute(Attribute::TARGET_PROPERTY)]
class Param
{
    public function __construct(
        public string $name,
        public array $rules)
    {}
}

测试request类

<?php
namespace App\Requests;

use App\Annotation\Param;

class UserRequest extends BaseRequest
{
    #[Param(name: 'username', rules: ['required', 'string', 'max:20'])]
    protected string $name;
    #[Param(name: 'secret', rules: ['required', 'string', 'min:6', 'max:20'])]
    protected string $secret;
    #[Param(name: 'type', rules: ['required', 'in:1,2,3'])]
    protected string $type;
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 2
lucifergit
public function __construct(
    public int $name,
    public array $rules)
{}

$name 为什么是int类型? 我看使用的时候,#[Param(name: 'type'....... name是字符串类型。

4天前 评论
code-- (楼主) 4天前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!