141. 注解验证

ThinkPHP支持使用注解方式定义路由和验证,需要安装额外的扩展:

composer require topthink/think-annotation

然后可以直接在控制器类的方法注释中定义,例如:

<?php
namespace app\controller;
use think\annotation\Route;
use think\annotation\route\Validate; 
use app\validate\IndexValidate; 
class Index
{
    /**
     * @Validate(IndexValidate::class,scene="create",batch="true")
     * @return mixed
     * @Route("hello")
     */
	public function hello()
    {
    	return 'hello, TP6 Annotation  Validate';
    }
}

@Route("hello/:name")@Validate(IndexValidate::class) 就是注解路由和验证器的内容,请务必注意注释的规范,不能在注解路由里面使用单引号,否则可能导致注解路由解析失败,可以利用IDE生成规范的注释。如果你使用PHPStorm的话,建议安装PHP Annotations插件:https://plugins.jetbrains.com/plugin/7320-php-annotations,可以支持注解的自动完成。

然后需要声明上面引用验证器类,例如:

<?php
namespace app\validate;
use think\Validate;
class IndexValidate extends Validate
{
    protected $rule = [
        'name' => 'require'
    ];
   protected $message = [
       'name.require' => '姓名必须填写',
   ];
    protected $scene = [
        'create' => ['name'],
    ];
}

该方式定义的路由在调试模式下面实时生效,部署模式则在第一次访问的时候生成注解缓存。

注解验证器参数说明

value参数,可以不写value=,直接抒写值就可以了

参数名 参数类型 参数默认值 参数说明
value string 验证器
scene string 验证场景
batch bool true 统一验证:true=是,flase=不是
message array [] 错误内容

错误访问示例:

http://127.0.0.1:8000/hello

页面输出

正确访问示例:

http://127.0.0.1:8000/hello?name=zhans

页面输出

下一节:ThinkPHP采用think\Cache类(实际使用think\facade\Cache类即可)提供缓存功能支持。

内置支持的缓存类型包括file、memcache、wincache、sqlite、redis。

ThinkPHP的缓存类遵循PSR-16规范。