侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Hyperf2.1框架中验证器的使用流程步骤

swoole  /  管理员 发布于 1年前   1217

官方手册上写着hyperf/validation 衍生于illuminate/validation,熟悉laravel的就不过多的介绍,不熟悉的自行搜索了解一下,我这里直接开始体验。


手册上也介绍了两种:

一.是创建表单验证类

对于复杂的验证场景,您可以创建一个 表单请求(FormRequest),表单请求是包含验证逻辑的一个自定义请求类,表单验证类会生成于 app\Request 目录下


二.手动创建验证器

如果您不想使用 表单请求(FormRequest) 的自动验证功能,可以通过注入 ValidatorFactoryInterface 接口类来获得验证器工厂类,然后通过 make 方法手动创建一个验证器实例


1.开始安装组件包

[root@hyperf hyperf-skeleton]# composer require hyperf/validation
Using version ^2.1 for hyperf/validation
./composer.json has been updated
Running composer update hyperf/validation
Loading composer repositories with package information
...
Generating optimized autoload files
> rm -rf runtime/container
68 packages you are using are looking for funding.
Use the `composer fund` command to find out more!


2.发布 Translation 组件的文件

[root@hyperf hyperf-skeleton]# php bin/hyperf.php vendor:publish hyperf/translation
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Config\Listener\RegisterPropertyHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Paginator\Listener\PageResolverListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\ExceptionHandler\Listener\ExceptionHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\DbConnection\Listener\RegisterConnectionResolverListener listener.
[hyperf/translation] publishes [config] successfully.


3.发布验证器组件的文件

[root@hyperf hyperf-skeleton]# php bin/hyperf.php vendor:publish hyperf/validation
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Config\Listener\RegisterPropertyHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Paginator\Listener\PageResolverListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\ExceptionHandler\Listener\ExceptionHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\DbConnection\Listener\RegisterConnectionResolverListener listener.
[hyperf/validation] publishes [zh_CN] successfully.
[hyperf/validation] publishes [en] successfully.


4.添加中间件 (在config/autoload/middlewares.php文件中)

return [
    'http' => [
        // 数组内配置您的全局中间件,顺序根据该数组的顺序
        \Hyperf\Validation\Middleware\ValidationMiddleware::class
    ],
];


5.添加异常处理器 (在config/autoload/exceptions.php文件中)

return [
    'handler' => [
        'http' => [
            \Hyperf\Validation\ValidationExceptionHandler::class,
        ],
    ],
];

这里测试方式1 (就用登录控制器测试) 

创建表单验证类

[root@hyperf hyperf-skeleton]# php bin/hyperf.php gen:request FooRequest
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Config\Listener\RegisterPropertyHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Paginator\Listener\PageResolverListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\ExceptionHandler\Listener\ExceptionHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\DbConnection\Listener\RegisterConnectionResolverListener listener.
App\Request\FooRequest created successfully.

启动hyperf框架

[root@hyperf hyperf-skeleton]# php bin/hyperf.php start

在app\Request\FooRequest.php中配置规则

    public function rules(): array
    {
        return [
            'email' => 'required|email',
            'password' => 'required|min:6|max:12',
        ];
    }


控制器UserController.php中使用 (其他代码已删除)

<?php
declare(strict_types=1);
namespace App\Controller;

use App\Request\FooRequest;
class UserController extends AbstractController
{
    public function login(FooRequest $request)
    {
            // 获取通过验证的数据...
            $validated = $request->validated();
     }
}

这就完了 通过不了规则 直接提示规则信息


我们在测试方式2  

手动创建验证器

同样的控制器UserController.php中使用

<?php
declare(strict_types=1);
namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
class UserController extends AbstractController
{
    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;
    public function login(RequestInterface $request)
    {
            // 获取通过验证的数据...
            //$validated = $request->validated();
            $validator = $this->validationFactory->make(
                $request->all(),
                [
                    'email' => 'required|email',
                    'password' => 'required|min:6|max:12',
                ]
            );
            if ($validator->fails()){
                // Handle exception
                $data = array('error' => 0, 'info' => $validator->errors()->first());
                return $data;
            }


一般简单的验证就用这个,方便 

看看效果

1.png




  • 上一条:
    Hyperf2.1版本自定义函数的编写流程步骤及使用
    下一条:
    如何才能使一个良好的结构在Laravel框架项目中呢?介绍一下HMVC模式跟nwidart/laravel modules这个包
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在hyperf框架中使用基于protobuf的RPC生成器实现rpc服务(0个评论)
    • hyperf + 京东联盟sdk实现简单商品列表转链跳转购买商品功能示例(0个评论)
    • Hyperf 3.0版本发布(0个评论)
    • hyperf2.2框架中添加Cache代理类的流程步骤及使用案例(0个评论)
    • hyperf2.1框架使用Dockerfile部署流程步骤(0个评论)
    • 近期文章
    • 在laravel框架中的5个HTTP客户端技巧分享(0个评论)
    • 在go语言中使用FFmpeg库实现PCM音频文件编码为mp3格式文件流程步骤(0个评论)
    • gopacket免安装Pcap实现驱动层流量抓包流程步骤(0个评论)
    • 在laravel项目中实现密码强度验证功能推荐扩展包:password-strength(0个评论)
    • 在go语言中用filepath.Match()函数以通配符模式匹配字符串示例(0个评论)
    • Laravel Response Classes 响应类使用优化浅析(0个评论)
    • mysql中sql_mode的各模式浅析(0个评论)
    • 百度文心一言今天发布,个人第一批内测体验记录,不好别打我(0个评论)
    • 嘿加密世界让我们谈谈在共识中将中本聪主流化(0个评论)
    • 在go语言中寻找两个切片或数组中的相同元素/共同点/交集并集示例代码(0个评论)
    • 近期评论
    • 博主 在

      2023年国务院办公厅春节放假通知:1月21日起休7天中评论 @ xiaoB 你只管努力,剩下的叫给天意;天若有情天亦老,..
    • xiaoB 在

      2023年国务院办公厅春节放假通知:1月21日起休7天中评论 会不会春节放假后又阳一次?..
    • BUG4 在

      你翻墙过吗?国内使用vpn翻墙可能会被网警抓,你需了解的事中评论 不是吧?..
    • 博主 在

      go语言+beego框架中获取get,post请求的所有参数中评论 @ t1  直接在router.go文件中配就ok..
    • Jade 在

      如何在MySQL查询中获得当月记录中评论 Dear zongscan.com team, We can skyroc..
    • 2017-09
    • 2020-03
    • 2020-06
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-11
    • 2022-03
    • 2022-05
    • 2023-01
    • 2023-02
    • 2023-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客