**思路:**
控制器:路由作用,基本访问流程,定义返回数据格式
验证码:验证提交的数据
模型:所有数据库表的操作(按表建,一张表的操作尽量都在同一个文件里)
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: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
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);
}
}
}
}
}
```
- 空白目录
- 使用thinkphp6搭建后端api接口流程
- tp6 uniapp vue 前后端跨域解决方案
- 操作记录
- api00
- 你看看有没有用
- 6666
- Docker安装LNMP环境的详细过程(可部署TP项目)
- LNMP部署thinkphp
- 玩客云Armbian 安装LNMP环境 Docker
- ThinkPHP6项目基操(16.实战部分 redis+token登录)
- ThinkPHP6项目基操(11.实战部分 部署后台静态页面模板及后台登录页面)
- ThinkPHP6项目基操(13.实战部分 项目中的自定义异常处理总结 错误页面API错误)
- ThinkPHP6项目基操(14.实战部分 中间件处理登录流程)
- ThinkPHP6项目基操(12.实战部分 验证码)
- ThinkPHP6项目基操(18.实战部分 表单令牌Token 防CSRF)
- ThinkPHP6项目基操(19.实战部分 Mysql模型事务操作)
- ThinkPHP6项目基操(20.实战部分 数据库操作返回值总结)
- 浏览器端判断当前设备的运行环境
- api
- api异常捕捉
- 写一个中间件
- 统一的参数返回形式
- ThinkPHP6调用模型的方法
- thinkphp6控制器、验证器、模型、service,各层写的内容