hyperf 验证 trait | php 技术论坛-大发黄金版app下载

模仿laravelvalidatesrequest写的一个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

: 1:

5年前

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