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

相关文章

Redis实现高效内存管理的示例代码

《Redis实现高效内存管理的示例代码》Redis内存管理是其核心功能之一,为了高效地利用内存,Redis采用了多种技术和策略,如优化的数据结构、内存分配策略、内存回收、数据压缩等,下面就来详细的介绍... 目录1. 内存分配策略jemalloc 的使用2. 数据压缩和编码ziplist示例代码3. 优化的

Python 基于http.server模块实现简单http服务的代码举例

《Python基于http.server模块实现简单http服务的代码举例》Pythonhttp.server模块通过继承BaseHTTPRequestHandler处理HTTP请求,使用Threa... 目录测试环境代码实现相关介绍模块简介类及相关函数简介参考链接测试环境win11专业版python

Python从Word文档中提取图片并生成PPT的操作代码

《Python从Word文档中提取图片并生成PPT的操作代码》在日常办公场景中,我们经常需要从Word文档中提取图片,并将这些图片整理到PowerPoint幻灯片中,手动完成这一任务既耗时又容易出错,... 目录引言背景与需求解决方案概述代码解析代码核心逻辑说明总结引言在日常办公场景中,我们经常需要从 W

使用Spring Cache本地缓存示例代码

《使用SpringCache本地缓存示例代码》缓存是提高应用程序性能的重要手段,通过将频繁访问的数据存储在内存中,可以减少数据库访问次数,从而加速数据读取,:本文主要介绍使用SpringCac... 目录一、Spring Cache简介核心特点:二、基础配置1. 添加依赖2. 启用缓存3. 缓存配置方案方案

MySQL的配置文件详解及实例代码

《MySQL的配置文件详解及实例代码》MySQL的配置文件是服务器运行的重要组成部分,用于设置服务器操作的各种参数,下面:本文主要介绍MySQL配置文件的相关资料,文中通过代码介绍的非常详细,需要... 目录前言一、配置文件结构1.[mysqld]2.[client]3.[mysql]4.[mysqldum

Python多线程实现大文件快速下载的代码实现

《Python多线程实现大文件快速下载的代码实现》在互联网时代,文件下载是日常操作之一,尤其是大文件,然而,网络条件不稳定或带宽有限时,下载速度会变得很慢,本文将介绍如何使用Python实现多线程下载... 目录引言一、多线程下载原理二、python实现多线程下载代码说明:三、实战案例四、注意事项五、总结引

IDEA与MyEclipse代码量统计方式

《IDEA与MyEclipse代码量统计方式》文章介绍在项目中不安装第三方工具统计代码行数的方法,分别说明MyEclipse通过正则搜索(排除空行和注释)及IDEA使用Statistic插件或调整搜索... 目录项目场景MyEclipse代码量统计IDEA代码量统计总结项目场景在项目中,有时候我们需要统计

MySQL设置密码复杂度策略的完整步骤(附代码示例)

《MySQL设置密码复杂度策略的完整步骤(附代码示例)》MySQL密码策略还可能包括密码复杂度的检查,如是否要求密码包含大写字母、小写字母、数字和特殊字符等,:本文主要介绍MySQL设置密码复杂度... 目录前言1. 使用 validate_password 插件1.1 启用 validate_passwo

MySQL实现多源复制的示例代码

《MySQL实现多源复制的示例代码》MySQL的多源复制允许一个从服务器从多个主服务器复制数据,这在需要将多个数据源汇聚到一个数据库实例时非常有用,下面就来详细的介绍一下,感兴趣的可以了解一下... 目录一、多源复制原理二、多源复制配置步骤2.1 主服务器配置Master1配置Master2配置2.2 从服

Go语言使用net/http构建一个RESTful API的示例代码

《Go语言使用net/http构建一个RESTfulAPI的示例代码》Go的标准库net/http提供了构建Web服务所需的强大功能,虽然众多第三方框架(如Gin、Echo)已经封装了很多功能,但... 目录引言一、什么是 RESTful API?二、实战目标:用户信息管理 API三、代码实现1. 用户数据