php注释验证,注解验证 · ThinkPHP6.0完全开发手册 · 看云
## 注解驗證器
ThinkPHP支持使用注解方式定義路由和驗證,需要安裝額外的擴展:
```
composer require topthink/think-annotation
```
然后可以直接在控制器類的方法注釋中定義,例如:
~~~
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)` 就是注解路由和驗證器的內(nèi)容,請務(wù)必注意注釋的規(guī)范,不能在注解路由里面使用單引號,否則可能導(dǎo)致注解路由解析失敗,可以利用IDE生成規(guī)范的注釋。如果你使用`PHPStorm`的話,建議安裝`PHP Annotations`插件:[https://plugins.jetbrains.com/plugin/7320-php-annotations](https://plugins.jetbrains.com/plugin/7320-php-annotations),可以支持注解的自動完成。
然后需要聲明上面引用驗證器類,例如:
~~~
namespace app\validate;
use think\Validate;
class IndexValidate extends Validate
{
protected $rule = [
'name' => 'require'
];
protected $message = [
'name.require' => '姓名必須填寫',
];
protected $scene = [
'create' => ['name'],
];
}
~~~
>[danger] 該方式定義的路由在調(diào)試模式下面實時生效,部署模式則在第一次訪問的時候生成注解緩存。
### 注解驗證器參數(shù)說明
> `value`參數(shù),可以不寫`value=`,直接抒寫值就可以了
| 參數(shù)名 | 參數(shù)類型 | 參數(shù)默認值 | 參數(shù)說明 |
| --- | --- | --- | --- |
| value | string | | 驗證器 |
| scene | string | | 驗證場景 |
| batch | bool | true | 統(tǒng)一驗證:true=是,flase=不是 |
| message | array | [] | 錯誤內(nèi)容 |
### 錯誤訪問示例:
~~~
http://127.0.0.1:8000/hello
~~~
頁面輸出

### 正確訪問示例:
~~~
http://127.0.0.1:8000/hello?name=zhans
~~~
頁面輸出

總結(jié)
以上是生活随笔為你收集整理的php注释验证,注解验证 · ThinkPHP6.0完全开发手册 · 看云的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决用户登录、注册传输中账号密码的安全泄
- 下一篇: 手机端页面,隐藏虚拟键盘