thinkphp5.1 注解插件

浏览:1589 发布日期:2020/01/02 分类:功能实现 关键字: 控制器 模型 注解 对象注入 验证器 参数过滤器 事务
thinkphp5.1
v0.1.0版本用注解的方式在控制器中实现:
数据验证
获取参数
属性对象注入
dev-master版本还支持:
自动事务
方法数据缓存
模型属性对象注入
示例文档https://www.cnblogs.com/cshaptx4869/p/12178960.html

如果您觉得好用,点个star哈
github地址:https://github.com/cshaptx4869/thinkphp-annotation安装composer require cshaptx4869/thinkphp-annotation配置
tags.php 添加行为'action_begin' => [
     \Fairy\ControllerAnnotationScaner::class
]
添加 system.php 配置文件(可选)return [
    'annotation' => [
        'cache' => false,//是否开启注解读取缓存
        'writelist' => []//注解读取白名单
    ]
]
支持的注解注解名    申明范围    作用
@Autowire    属性    自动注入类对象
@DynamicAutowire    方法    声明当前方法允许属性注入的类
@IgnoreAutowire    方法    声明当前方法忽略属性注入的类
@RequestParam    方法    过滤、格式化请求参数
@Validator    方法    验证器验证
使用<?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
{
    /**
     * 属性对象注入
     * class: 类名(必填) string类型
     * @Autowire(class=ArticleModel::class)
     */
    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类型
     * @RequestParam(
     *     fields={"title","image_url","content","is_temporary","extra":"默认值"},
     *     mapping={"image_url":"img_url"},
     *     method="post"
     * )
     */
    public function save(Request $request)
    {
        //获取过滤过后的参数
        $postData = $request->requestParam;

        return MyToolkit::success($this->articleModel->store($postData));
    }
}
评论( 相关
后面还有条评论,点击查看>>