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 AppValidator; use AppAnnotationMappingAlphaDash; use SwoftValidatorAnnotationMappingIsInt; use SwoftValidatorAnnotationMappingIsString; use SwoftValidatorAnnotationMappingValidator; /** * 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' => [ AppHttpMiddlewareFavIconMiddleware::class, SwoftHttpSessionSessionMiddleware::class, // SwoftWhoopsWhoopsMiddleware::class, // Allow use @View tag SwoftViewMiddlewareViewMiddleware::class, AppHttpMiddlewareAuthMiddleware::class ], 'afterMiddlewares' => [ SwoftHttpServerMiddlewareValidatorMiddleware::class, AppHttpMiddlewareAfterMiddleware::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