buildAdmin 后端控制器的代码分析

2023-11-20 17:52

本文主要是介绍buildAdmin 后端控制器的代码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

buildAdmin的代码生成,很像是 fastadmin 的生成模式,当我们利用数据库生成了一个控制器的时候,我们可以看到, 它的生成代码很简洁


<?phpnamespace app\admin\controller\askanswer;use app\common\controller\Backend;/*** 回答管理*/
class Answer extends Backend     //控制器继承了 backend
{/*** Answer模型对象* @var object* @phpstan-var \app\admin\model\Answer*///定义了一个 模型对象,也就是对应数据表的 模型protected object $model;//这里是在添加数据中 排除了一些,自动生成的字段,  在Backend中,有对这些字段的调用protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];//这里是设置了前端的快速搜索protected string|array $quickSearchField = ['id'];public function initialize(): void{parent::initialize(); //这里用了父类的 初始化方法, 做了一些 用户认证,权限判断,数据库连接检测等$this->model = new \app\admin\model\Answer;$this->request->filter('clean_xss');  //这里对 request 做了一次 xss 攻击的过滤}/*** 若需重写查看、编辑、删除等方法,请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写*/
}

接着我们来到,父类, backend
在这里插入图片描述
在追代码的过程中,我没有看到 跨域的操作, 因为fastadmin 在这里面是有跨域操作的一段代码的,后来经过 整块代码搜索, 才想起来, 这是tp8了, 是有中间键的,而fastadmin中是tp5.0,没有中间键的
在这里插入图片描述
真正的 增,删,改,查的代码 就在traits中

<?phpnamespace app\admin\library\traits;use Throwable;
use think\facade\Config;/*** 后台控制器trait类* 已导入到 @see \app\common\controller\Backend 中* 若需修改此类方法:请复制方法至对应控制器后进行重写*/
trait Backend
{/*** 排除入库字段* @param array $params* @return array*/protected function excludeFields(array $params): array{if (!is_array($this->preExcludeFields)) {$this->preExcludeFields = explode(',', (string)$this->preExcludeFields);}foreach ($this->preExcludeFields as $field) {if (array_key_exists($field, $params)) {unset($params[$field]);}}return $params;}/*** 查看* @throws Throwable*/public function index(): void{if ($this->request->param('select')) {$this->select();}list($where, $alias, $limit, $order) = $this->queryBuilder();$res = $this->model->field($this->indexField)->withJoin($this->withJoinTable, $this->withJoinType)->alias($alias)->where($where)->order($order)->paginate($limit);$this->success('', ['list'   => $res->items(),'total'  => $res->total(),'remark' => get_route_remark(),]);}/*** 添加*/public function add(): void{if ($this->request->isPost()) {$data = $this->request->post();if (!$data) {$this->error(__('Parameter %s can not be empty', ['']));}$data = $this->excludeFields($data);if ($this->dataLimit && $this->dataLimitFieldAutoFill) {$data[$this->dataLimitField] = $this->auth->id;}$result = false;$this->model->startTrans();try {// 模型验证if ($this->modelValidate) {$validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));if (class_exists($validate)) {$validate = new $validate;if ($this->modelSceneValidate) $validate->scene('add');$validate->check($data);}}$result = $this->model->save($data);$this->model->commit();} catch (Throwable $e) {$this->model->rollback();$this->error($e->getMessage());}if ($result !== false) {$this->success(__('Added successfully'));} else {$this->error(__('No rows were added'));}}$this->error(__('Parameter error'));}/*** 编辑* @throws Throwable*/public function edit(): void{$id  = $this->request->param($this->model->getPk());$row = $this->model->find($id);if (!$row) {$this->error(__('Record not found'));}$dataLimitAdminIds = $this->getDataLimitAdminIds();if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {$this->error(__('You have no permission'));}if ($this->request->isPost()) {$data = $this->request->post();if (!$data) {$this->error(__('Parameter %s can not be empty', ['']));}$data   = $this->excludeFields($data);$result = false;$this->model->startTrans();try {// 模型验证if ($this->modelValidate) {$validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));if (class_exists($validate)) {$validate = new $validate;if ($this->modelSceneValidate) $validate->scene('edit');$validate->check($data);}}$result = $row->save($data);$this->model->commit();} catch (Throwable $e) {$this->model->rollback();$this->error($e->getMessage());}if ($result !== false) {$this->success(__('Update successful'));} else {$this->error(__('No rows updated'));}}$this->success('', ['row' => $row]);}/*** 删除* @param array $ids* @throws Throwable*/public function del(array $ids = []): void{if (!$this->request->isDelete() || !$ids) {$this->error(__('Parameter error'));}$where             = [];$dataLimitAdminIds = $this->getDataLimitAdminIds();if ($dataLimitAdminIds) {$where[] = [$this->dataLimitField, 'in', $dataLimitAdminIds];}$pk      = $this->model->getPk();$where[] = [$pk, 'in', $ids];$count = 0;$data  = $this->model->where($where)->select();$this->model->startTrans();try {foreach ($data as $v) {$count += $v->delete();}$this->model->commit();} catch (Throwable $e) {$this->model->rollback();$this->error($e->getMessage());}if ($count) {$this->success(__('Deleted successfully'));} else {$this->error(__('No rows were deleted'));}}/*** 排序* @param int $id       排序主键值* @param int $targetId 排序位置主键值* @throws Throwable*/public function sortable(int $id, int $targetId): void{$dataLimitAdminIds = $this->getDataLimitAdminIds();if ($dataLimitAdminIds) {$this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);}$row    = $this->model->find($id);$target = $this->model->find($targetId);if (!$row || !$target) {$this->error(__('Record not found'));}if ($row[$this->weighField] == $target[$this->weighField]) {$autoSortEqWeight = is_null($this->autoSortEqWeight) ? Config::get('buildadmin.auto_sort_eq_weight') : $this->autoSortEqWeight;if (!$autoSortEqWeight) {$this->error(__('Invalid collation because the weights of the two targets are equal'));}// 自动重新整理排序$all = $this->model->select();foreach ($all as $item) {$item[$this->weighField] = $item[$this->model->getPk()];$item->save();}unset($all);// 重新获取$row    = $this->model->find($id);$target = $this->model->find($targetId);}$backup                    = $target[$this->weighField];$target[$this->weighField] = $row[$this->weighField];$row[$this->weighField]    = $backup;$row->save();$target->save();$this->success();}/*** 加载为select(远程下拉选择框)数据,默认还是走$this->index()方法* 必要时请在对应控制器类中重写*/public function select(): void{}
}

这篇关于buildAdmin 后端控制器的代码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/396386

相关文章

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

MySQL进行数据库审计的详细步骤和示例代码

《MySQL进行数据库审计的详细步骤和示例代码》数据库审计通过触发器、内置功能及第三方工具记录和监控数据库活动,确保安全、完整与合规,Java代码实现自动化日志记录,整合分析系统提升监控效率,本文给大... 目录一、数据库审计的基本概念二、使用触发器进行数据库审计1. 创建审计表2. 创建触发器三、Java

SpringBoot中六种批量更新Mysql的方式效率对比分析

《SpringBoot中六种批量更新Mysql的方式效率对比分析》文章比较了MySQL大数据量批量更新的多种方法,指出REPLACEINTO和ONDUPLICATEKEY效率最高但存在数据风险,MyB... 目录效率比较测试结构数据库初始化测试数据批量修改方案第一种 for第二种 case when第三种

解决1093 - You can‘t specify target table报错问题及原因分析

《解决1093-Youcan‘tspecifytargettable报错问题及原因分析》MySQL1093错误因UPDATE/DELETE语句的FROM子句直接引用目标表或嵌套子查询导致,... 目录报js错原因分析具体原因解决办法方法一:使用临时表方法二:使用JOIN方法三:使用EXISTS示例总结报错原

MySQL中的LENGTH()函数用法详解与实例分析

《MySQL中的LENGTH()函数用法详解与实例分析》MySQLLENGTH()函数用于计算字符串的字节长度,区别于CHAR_LENGTH()的字符长度,适用于多字节字符集(如UTF-8)的数据验证... 目录1. LENGTH()函数的基本语法2. LENGTH()函数的返回值2.1 示例1:计算字符串

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

一文详解SpringBoot中控制器的动态注册与卸载

《一文详解SpringBoot中控制器的动态注册与卸载》在项目开发中,通过动态注册和卸载控制器功能,可以根据业务场景和项目需要实现功能的动态增加、删除,提高系统的灵活性和可扩展性,下面我们就来看看Sp... 目录项目结构1. 创建 Spring Boot 启动类2. 创建一个测试控制器3. 创建动态控制器注

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性: