Swoft-Api项目部署七:验证器
woft验证器,比thinkphp的验证器难搞很多。非注解式验证就很简单了
一:创建验证器
位置:app/Validator/TestValidator.php
<?php declare(strict_types=1); /** * This file is part of Swoft. * * @link https://swoft.org * @document https://swoft.org/docs * @contact group@swoft.org * @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE */ namespace App\Validator; use App\Annotation\Mapping\AlphaDash; use Swoft\Validator\Annotation\Mapping\IsInt; use Swoft\Validator\Annotation\Mapping\IsString; use Swoft\Validator\Annotation\Mapping\Validator; /** * Class TestValidator * * @since 2.0 * * @Validator(name="TestValidator") */ class TestValidator { /** * @IsString() * * @var string */ protected $name = 'defualtName'; /** * @IsInt(message="type must Integer") * * @var int */ protected $type; /** * @IsString() * @AlphaDash(message="Passwords can only be alphabet, numbers, dashes, underscores") * * @var string */ protected $password; /** * @IsString(message="tille 必须为字符串") * * @var string * */ protected $title; /** * @IsString(message="content 必须为字符串") * * @var string */ protected $content; }
二:加载验证器
'httpDispatcher' => [ // Add global http middleware 'middlewares' => [ \App\Http\Middleware\FavIconMiddleware::class, \Swoft\Http\Session\SessionMiddleware::class, // \Swoft\Whoops\WhoopsMiddleware::class, // Allow use @View tag \Swoft\View\Middleware\ViewMiddleware::class, \App\Http\Middleware\AuthMiddleware::class ], 'afterMiddlewares' => [ \Swoft\Http\Server\Middleware\ValidatorMiddleware::class, \App\Http\Middleware\AfterMiddleware::class ] ],
三:控制器调用验证器(非注解形式)
/** * 仅验证TestValidator验证器中的 type 字段 * @RequestMapping() * @param Request $request * * @return array */ public function t36(Request $request) { $data= [ 'name'=>1, 'type'=>'sdfsdfsdfsdfsdf' ]; # 只验证type字段 $s = validate($data,"TestValidator",['type']); # 此处会验证所有字段 # $s = validate($data,"TestValidator"); var_dump($s); }
输出结果(直接会打印字符串):type must Integer
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2016-09-03 thinkphp 3.2 join
2013-09-03 ajax传输 基础一
2013-09-03 获取ip的ip138.com