thinkphp5.1中用注解的方式实现:
数据验证器
涮选获取、格式化参数
属性对象自动注入
自动事务
使用:
ArticleController 控制器
<?php
namespace app\index\controller;
use app\index\validate\Article\SaveValidate;
use app\common\model\ArticleModel;
// 引入对应的注解
use Fairy\Annotation\Autowire;
use Fairy\Annotation\RequestParam;
use Fairy\Annotation\Validator;
use think\Request;
class ArticleController
{
/**
* 属性对象注入
* @Autowire()
* @var ArticleModel
*/
public $articleModel;
/**
* 数据验证
* clsss: thinkphp定义的验证器类名(必填) string类型
* scene: 验证场景名 string类型
* batch:是否批量验证 bool类型
* throw: 验证失败是否抛出异常 bool类型
* @Validator(
* class="SaveValidate"::class,
* scene="save",
* batch=false,
* throw=false
* )
*
* 获取参数
* fields: 定义要获取的字段名,可批量设置默认值 array类型
* mapping: 转换前台传递的字段名为自定义的字段名 array类型
* method: 获取参数的方法,支持get、post、put、delte string类型
* json: 格式化json字段的数据 array类型
*
* json使用示例:
* json:{field1,field2,...fieldn}
* 表示格式化field1,field2,...,字段的json数据
*
* 支持json一维和二维字段的涮选,如
* json:{field1:{childField1,childField2...}}
* 表示格式化field1字段的json数据,并只获取field1字段下的childField1和childField2下标的值(支持深度一维和二维,会自动识别)
*
* @RequestParam(
* fields={"title","image_url","content","category_id","is_temporary","extra":"默认值"},
* json={"category_id"},
* mapping={"image_url":"img_url"},
* method="post"
* )
*/
public function save(Request $request)
{
//获取过滤过后的参数
$postData = $request->requestParam;
return MyToolkit::success($this->articleModel->store($postData));
}
}AaaModel 模型
<?php
namespace app\common\model;
use Fairy\Annotation\Autowire;
use Fairy\Annotation\Transaction;
use Fairy\ModelAnnotationScaner;
use think\Db;
use think\Model;
class AaaModel extends Model
{
// 模型中使用Autowire注解的trait
use ModelAnnotationScaner;
/**
* @Autowire()
* @var AccountModel
*/
public $accountModel;
/**
* 注解控制事务
* 返回值等价于true commit 否则 rollback
* @Transaction()
*/
public function store()
{
return Db::name('aaa')->insert(['id' => 14, 'username' => 'bob']) > 0;
}
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号