首页 > 编程语言 >thinkphp6控制器、验证器、模型、service,各层写的内容

thinkphp6控制器、验证器、模型、service,各层写的内容

时间:2023-01-06 18:23:59浏览次数:49  
标签:return service 各层 agreement thinkphp6 params model id card

思路:

控制器:路由作用,基本访问流程,定义返回数据格式

验证码:验证提交的数据

模型:所有数据库表的操作(按表建,一张表的操作尽量都在同一个文件里)

service:公共的逻辑

 

代码:

控制器

 app\admin\controller\config\CardAgreement.php

<?php
/*
 * @Author: yhy
 * @Date: 2023-01-06 09:43:23
 * @FilePath: \backend-shop\app\admin\controller\config\CardAgreement.php
 * @Description: 卡项协议 控制器
 * 
 */
declare(strict_types=1);

namespace app\admin\controller\config;

use app\admin\controller\Controller;
use app\admin\model\config\CardAgreement as CardAgreementModel;
use app\admin\validate\config\CardAgreement as CardAgreementValidate;
use think\App;

class CardAgreement extends Controller
{
    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new CardAgreementModel();
    }

    /**
     * 列表
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function index()
    {
        $params = $this->postForm() ?? []; 
        $list = $this->model->getList($params);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 添加
     * @return array
     */
    public function add()
    {
        $params = $this->postForm() ?? [];
        validate(CardAgreementValidate::class)->scene('add')->check($params);
        if ($this->model->add($params)) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($this->model->getError() ?: '添加失败');
    }

    /**
     * 编辑
     * @return array
     */
    public function edit()
    {
        // 模板详情
        $params = $this->postForm() ?? [];
        validate(CardAgreementValidate::class)->scene('edit')->check($params);
        // 更新记录
        if ($this->model->edit($params)) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($this->model->getError() ?: '更新失败');
    }
    
    /**
     * 获取详情记录   
     * @return array
     */
    public function detail()
    {
        $params = $this->postForm() ?? [];
        validate(CardAgreementValidate::class)->scene('detail')->check($params);
        $info = $this->model->detail((int)$params['card_agreement_id']);
        return $this->renderSuccess(compact('info'));
    }

    /**
     * @description: 修改状态
     * @return {*}
     */    
    public function checkStatus()
    {
        $params = $this->postForm() ?? [];
        validate(CardAgreementValidate::class)->scene('status')->check($params);
        if ($this->model->checkStatus($params)) {
            return $this->renderSuccess('修改成功');
        }
        return $this->renderError($this->model->getError() ?: '修改失败');
    }

    /**
     * 删除  
     * @return array
     */
    public function delete()
    {
        $params = $this->postForm() ?? [];
        validate(CardAgreementValidate::class)->scene('delete')->check($params);
        if (!$this->model->omit($params)) {
            return $this->renderError($this->model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }
}

 

验证器 app\admin\validate\config\CardAgreement.php
<?php
/*
 * @Author: yhy
 * @Date: 2023-01-06 09:43:39
 * @FilePath: \backend-shop\app\admin\validate\config\CardAgreement.php
 * @Description: 卡项协议 验证器
 * 
 */
namespace app\admin\validate\config;

use app\admin\model\config\CardAgreement as CardAgreementModel;
use app\admin\model\Store;
use think\Validate as V;

class CardAgreement extends V
{
    //当前验证规则
    protected $rule = [
        'card_agreement_id|ID' => 'require|integer',
        'name|名称' => 'require|min:2|max:20|checkName',
        'type|类型' => 'require|in:10,20,30,40|integer',
        'content|协议内容' => 'require|min:1|max:10000',
        'status|状态' => 'require|in:10,20|integer',
        'store_ids|适用商城' => 'require|array|checkStoreList',
        'search|搜索' => 'min:1|max:20',
    ];

    //验证场景定义
    protected $scene = [
        'add'  =>  ['name','type','content','status','store_ids'],
        'edit'  =>  ['card_agreement_id','name','type','content','status','store_ids'],
        'detail' => ['card_agreement_id'],
        'delete' => ['card_agreement_id'],
        'status' => ['card_agreement_id','status'],
        'list' => ['search'],
    ];

    // 自定义验证规则
    protected function checkName($value, $rule, $data=[])
    {
        if (!empty($data['card_agreement_id'])) {
            $bool = CardAgreementModel::where('card_agreement_id','<>',$data['card_agreement_id'])
                ->where('name','=',$value)
                ->find();
        } else {
            $bool = CardAgreementModel::where('name','=',$value)
                ->find();
        }
        if ($bool) {
            return '名称已存在';
        }
        return true;
    }

     /**
     * @description: 验证商城id和区域id
     * @param {*} $value
     * @return {*}
     */    
    public function checkStoreList($value)
    {
        //数据处理
        if(empty($value)){
            return '请选择商城';
        }
        //判定每个商城是否存在
        if(count($value) != Store::inNum($value)){
            return '部分商城已经不存在';
        }
        return true;
    }

}

 

模型

app\admin\model\config\CardAgreement.php

<?php
/*
 * @Author: yhy
 * @Date: 2023-01-06 09:43:33
 * @FilePath: \backend-shop\app\admin\model\config\CardAgreement.php
 * @Description: 卡项协议 model
 * 
 */
declare (strict_types=1);

namespace app\admin\model\config;

use app\common\model\config\CardAgreement as CardAgreementCommon;
use think\facade\Db;

class CardAgreement extends CardAgreementCommon
{
    /**
     * 获取列表记录
     * @param array $params
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $params = []): \think\Paginator
    {
        // 检索查询条件
        $filter = $this->getFilter($params);
        // 查询列表数据
        return $this->where($filter)
            ->with(['card_agreement_store_rel.store'])
            ->hidden(['card_agreement_store_rel.store'])
            ->order(['create_time' => 'desc'])
            ->paginate(15);
    }

    /**
     * 检索查询条件
     * @param array $params
     * @return array
     */
    private function getFilter(array $params = []): array
    {
        $allowFilter = ['search',];
        // 默认查询条件
        $params = $this->setQueryDefaultValue($params, ['search' => '']);

        // 检索查询条件
        $filter[] = ['is_delete','=',self::IS_DELETE_NO];
        foreach($params as $key=>$value){
            if(!in_array($key,$allowFilter) || (empty($value) && $value!=0)) continue;
            if($key == 'search'){
                !empty($params['search']) && $filter[] = ['name', 'like', "%{$params['search']}%"];
            }else{
                $filter[] = [$key,'=',$value];
            }
        }
        return $filter;
    }

    /**
     * 添加新记录
     * @param array $params
     * @return bool|false
     */
    public function add(array $params): bool
    {
        Db::startTrans();
        try {
            //添加协议表
            $this->allowField(['name','type','content','status'])->save($params);

            //添加与商城关联
            $card_agreement_store_rel_model = new CardAgreementStoreRel();
            $card_agreement_store_rel_model->increased($params['store_ids'],(int)$this->card_agreement_id);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $this->setError($e->getMessage());
            // 回滚事务
            Db::rollback();
            return false;
        }
        return true;
    }

    /**
     * 更新记录
     * @param array $params
     * @return bool
     */
    public function edit(array $params): bool
    {
        $model = $this->findOne((int)$params['card_agreement_id']);
        if($model){
            Db::startTrans();
            try {
                //修改协议表
                $model->allowField(['name','type','content','status'])->save($params);

                //添加与商城关联
                $card_agreement_store_rel_model = new CardAgreementStoreRel();
                $card_agreement_store_rel_model->where('card_agreement_id',$params['card_agreement_id'])->delete();
                $card_agreement_store_rel_model->increased($params['store_ids'],(int)$params['card_agreement_id']);

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                $this->setError($e->getMessage());
                // 回滚事务
                Db::rollback();
                return false;
            }
            return true;
        }
        return false;
    }


    /**
     * @description: 详情
     * @param {int} $id
     * @return {*}
     */    
    public function detail(int $id)
    {
        $model= $this->where('is_delete',self::IS_DELETE_NO)
            ->with(['card_agreement_store_rel.store'])
            ->hidden(['card_agreement_store_rel.store'])
            ->find($id);
        if(!$model){
            $this->setError('数据不存在');
            return false;
        }
        return $model;
    }

    /**
     * @description: 查询是否存在数据
     * @param {*} $id
     * @return {*}
     */
    public function findOne(int $id)
    {
        $model = $this->where('is_delete',self::IS_DELETE_NO)->find($id);
        if(!$model){
            $this->setError('数据不存在');
            return false;
        }
        return $model;
    }

     /**
     * @description: 修改状态
     * @param {*} $params
     * @return {*}
     */
    public function checkStatus($params)
    {
         //判定数据是否存在
         $model = $this->findOne((int)$params['card_agreement_id']);
         //修改状态
         return $model &&   $model->allowField(['status'])->save($params);
    }

     /**
     * @description: 删除
     * @param {array} $params
     * @return {*}
     */    
    public function omit(array $params)
    {
        $model = $this->findOne((int)$params['card_agreement_id']);
        if($model){
            Db::startTrans();
            try {
                  //删除协议
                  $model->is_delete = self::IS_DELETE_YES;
                  $model->save();

                  //删除 协议和商城关系
                  CardAgreementStoreRel::where('card_agreement_id',$params['card_agreement_id'])->delete();

                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                $this->setError($e->getMessage());
                // 回滚事务
                Db::rollback();
                return false;
            }
            return true;
        }
        return false;
    }
}

公共模型

app\common\model\config\CardAgreement.php

<?php
/*
 * @Author: yhy
 * @Date: 2023-01-06 09:43:45
 * @FilePath: \backend-shop\app\common\model\config\CardAgreement.php
 * @Description: 卡项协议 模型
 * 
 */
declare (strict_types=1);

namespace app\common\model\config;

use app\common\model\Base;
use think\model\relation\HasMany;

class CardAgreement extends Base
{
    // 定义表名
    protected $name = 'card_agreement';

    // 定义主键
    protected $pk = 'card_agreement_id';

    //类型:10次卡20充值卡30折扣卡40专项卡
    const CARD_TYPE_NUM = 10;
    const CARD_TYPE_RECHARGE = 20;
    const CARD_TYPE_DISCOUNT = 30;
    const CARD_TYPE_SPECIAL = 40;
    public static $cardTypeData = [
        self::CARD_TYPE_NUM => ["value" => self::CARD_TYPE_NUM,"text" => "次卡"],
        self::CARD_TYPE_RECHARGE => ["value" => self::CARD_TYPE_RECHARGE,"text" => "充值卡"],
        self::CARD_TYPE_DISCOUNT => ["value" => self::CARD_TYPE_DISCOUNT,"text" => "折扣卡"],
        self::CARD_TYPE_SPECIAL => ["value" => self::CARD_TYPE_SPECIAL,"text" => "专项卡"],
    ];
    public function getTypeAttr($value): array
    {
        return self::$cardTypeData[$value];
    }

    /**
     * @description: 修改器:内容
     * @param {*} $value
     * @return {*}
     */    
    public function getContentAttr($value)  
    {
        return htmlspecialchars_decode($value);
    }

    /**
     * @description: 关联适用商城
     * @return {*}
     */    
    public function CardAgreementStoreRel():HasMany
    {
        return $this->hasMany(CardAgreementStoreRel::class,'card_agreement_id','card_agreement_id');
    }

}

逻辑层

app\admin\service\Cache.php

<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <[email protected]>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\admin\service;

use app\common\service\BaseService;
use think\facade\Cache as CacheDriver;

/**
 * 清理缓存
 * Class Cache
 */
class Cache extends BaseService
{
    // 缓存驱动句柄
    /** @var $CacheDriver \think\Cache */
    private $cache;

    /**
     * 构造方法
     * Cache constructor.
     */
    public function initialize()
    {
        // 实例化缓存驱动
        $this->cache = CacheDriver::instance();
    }

    /**
     * 删除缓存
     * @param $data
     * @return bool
     */
    public function rmCache($data)
    {
        // 数据缓存
        if (in_array('data', $data['item'])) {
            // 强制模式
            $isForce = isset($data['isForce']) && (bool)$data['isForce'];
            // 清除缓存
            $isForce ? $this->cache->clear() : $this->cache->tag('cache')->clear();
        }
        // 临时文件
        if (in_array('temp', $data['item'])) {
            $paths = [
                'temp' => web_path() . 'temp/',
                'runtime' => runtime_root_path() . 'image/'
            ];
            foreach ($paths as $path) {
                $this->deleteFolder($path);
            }
        }
        return true;
    }

    /**
     * 递归删除指定目录下所有文件
     * @param $path
     * @return void
     */
    private function deleteFolder($path): void
    {
        if (!is_dir($path)) {
            return;
        }
        // 扫描一个文件夹内的所有文件夹和文件
        foreach (scandir($path) as $val) {
            // 排除目录中的.和..
            if (!in_array($val, ['.', '..', '.gitignore'])) {
                // 如果是目录则递归子目录,继续操作
                if (is_dir($path . $val)) {
                    // 子目录中操作删除文件夹和文件
                    $this->deleteFolder($path . $val . '/');
                    // 目录清空后删除空文件夹
                    rmdir($path . $val . '/');
                } else {
                    // 如果是文件直接删除
                    unlink($path . $val);
                }
            }
        }
    }
}

 

 

标签:return,service,各层,agreement,thinkphp6,params,model,id,card
From: https://www.cnblogs.com/hfdp/p/17031247.html

相关文章

  • Overt.GrpcTemplate.Service 模板使用教程
     1.Overt.GrpcTemplate.Service .NetCore3.1版本模板名称改成 Overt.GrpcTemplateV3.Service源码地址:https://github.com/overtly/template.gitidentity:Ov......
  • 解决.Net Runtime Optimization Service占用CPU的问题
      今天接到云主机的告警,说CPU占用率长期在100%,服务器是windows2012的系统,登录后看有个.NetRuntimeOptimizationService的进程把CPU全占了,之前没见过这个进程,经查询......
  • 『中级篇』docker-swarm中的Service创建维护和水平扩展(45)
    ​通过上一节已经创建了1个manager和2个worker,现在看看如何使用。源码地址:​​https://github.com/limingios/docker​​中的No.5;service的操作之前说docker-compose的时候......
  • 『中级篇』k8s的NodePort类型Service以及Label的简单实用(68)
    型,clusterIp,这次说下NodePort。源码:​​https://github.com/limingios/docker/tree/master/No.10​​通过pod创建service进入labs目录下的servicecddeployk8s-mastercdla......
  • 『中级篇』Docker service更新(52)
    ​serive更新其实并不是简单的更新,在swarm模式下的service都是在运行的,正在运行的进行更新,swarm是生产环境,我们不想因为更新中断咱们的业务,想的是不影响正常的业务开展。在......
  • 如何跳出springboot的service层中某一个方法?
    有一个需求,就是中断某个方法中的for循环目前的做法是:for循环中,增加if判断,如果满足条件就return,会中断这个方法for(inti=0;i<totalIndex;i++){............
  • android之调用webservice实现图片上传
    最近boss要求做android客户端的图片上传和下载,就是调用服务器的webservice接口,实现从android上传图片到服务器,然后从服务器下载图片到android客户端。需求下来......
  • android Service 的简单使用
    androidService的简单使用1、要使用Service,首先就是在配置文件里吗添加Service,如果不填加,你的Service是不能够使用的。目前学到的方法有两种  方法一:<serviceandroi......
  • android基础02 - 多媒体、多线程与异步任务、Service、网络
    多媒体通知通知渠道:程序对自己发出的通知进行分类,用户可根据渠道对消息进行屏蔽或设置响铃振动。一个应用的通知渠道一旦创建就无法再修改,只能再创建新的可在Activity、......
  • 图解 Retrofit - ServiceMethod
    通过​​Retrofit+RxAndroid实践总结​​,我们已经了解到了Retrofit的基本用法,为了知其所以然,我们以图解加源码的方式从ServiceMethod入手,逐步解析Retrofit。首先......