hyperf 十八 数据库 一

教程地址:Hyperf

一、安装

1.1 hyperf框架

composer require hyperf/db-connection

1.2 其他框架

composer require hyperf/database

二、配置

配置项类型默认值备注
driverstring数据库引擎
hoststring数据库地址
databasestring数据库默认 DB
usernamestring数据库用户名
passwordstringnull数据库密码
charsetstringutf8数据库编码
collationstringutf8_unicode_ci数据库编码
prefixstring''数据库模型前缀
timezonestringnull数据库时区
pool.min_connectionsint1连接池内最少连接数
pool.max_connectionsint10连接池内最大连接数
pool.connect_timeoutfloat10.0连接等待超时时间
pool.wait_timeoutfloat3.0超时时间
pool.heartbeatint-1心跳
pool.max_idle_timefloat60.0最大闲置时间
optionsarrayPDO 配置

 options相关pdo文档:PHP: PDO - Manual

三、多库配置、读写分离、原生查询、sql输出

 由于hyperf/database 衍生于 illuminate/database 。

illuminate/database多库配置和读写分离参考illuminate/database 使用 四-CSDN博客  ;原生查询和sql输出参考illuminate/database 使用 五-CSDN博客 。

3.1 原生查询-事务

3.1.1 自动管理数据库事务

                根据文档描述:如果事务的闭包 Closure 中出现一个异常,事务将会回滚。如果事务闭包 Closure 执行成功,事务将自动提交。

                确实比手动方便,但是还得查下报错怎么处理。

                根据之前文章,应该明白Illuminate\Database中调用顺序,即从Illuminate\Database\Capsule\Manager最后会调用到Illuminate\Database\Connectionl。Connectionl中调用Concerns\ManagesTransactions类。transaction()方法在ManagesTransactions类中被调用。

                源码如下

trait ManagesTransactions
{/*** Execute a Closure within a transaction.** @param  \Closure  $callback* @param  int  $attempts* @return mixed** @throws \Throwable*/public function transaction(Closure $callback, $attempts = 1){for ($currentAttempt = 1; $currentAttempt <= $attempts; $currentAttempt++) {$this->beginTransaction();// We'll simply execute the given callback within a try / catch block and if we// catch any exception we can rollback this transaction so that none of this// gets actually persisted to a database or stored in a permanent fashion.try {$callbackResult = $callback($this);}// If we catch an exception we'll rollback this transaction and try again if we// are not out of attempts. If we are out of attempts we will just throw the// exception back out and let the developer handle an uncaught exceptions.catch (Throwable $e) {$this->handleTransactionException($e, $currentAttempt, $attempts);continue;}try {if ($this->transactions == 1) {$this->getPdo()->commit();}$this->transactions = max(0, $this->transactions - 1);if ($this->transactions == 0) {optional($this->transactionsManager)->commit($this->getName());}} catch (Throwable $e) {$this->handleCommitTransactionException($e, $currentAttempt, $attempts);continue;}$this->fireConnectionEvent('committed');return $callbackResult;}}/*** Handle an exception encountered when running a transacted statement.** @param  \Throwable  $e* @param  int  $currentAttempt* @param  int  $maxAttempts* @return void** @throws \Throwable*/protected function handleTransactionException(Throwable $e, $currentAttempt, $maxAttempts){// On a deadlock, MySQL rolls back the entire transaction so we can't just// retry the query. We have to throw this exception all the way out and// let the developer handle it in another way. We will decrement too.if ($this->causedByConcurrencyError($e) &&$this->transactions > 1) {$this->transactions--;optional($this->transactionsManager)->rollback($this->getName(), $this->transactions);throw $e;}// If there was an exception we will rollback this transaction and then we// can check if we have exceeded the maximum attempt count for this and// if we haven't we will return and try this query again in our loop.$this->rollBack();if ($this->causedByConcurrencyError($e) &&$currentAttempt < $maxAttempts) {return;}throw $e;}
/*** Handle an exception encountered when committing a transaction.** @param  \Throwable  $e* @param  int  $currentAttempt* @param  int  $maxAttempts* @return void** @throws \Throwable*/protected function handleCommitTransactionException(Throwable $e, $currentAttempt, $maxAttempts){$this->transactions = max(0, $this->transactions - 1);if ($this->causedByConcurrencyError($e) &&$currentAttempt < $maxAttempts) {return;}if ($this->causedByLostConnection($e)) {$this->transactions = 0;}throw $e;}……
}

如源码所示,闭包执行错误,执行handleTransactionException()方法,处理回滚,并抛出异常。

$this->transactions--大概是处理事务嵌套相关代码。

提交异常,执行handleCommitTransactionException()方法,嵌套事务大概会继续执行,最后抛出异常。

测试代码

function test4()
{Capsule::transaction(function () {Capsule::table('userinfo')->where(['id' => 1])->update(['votes' => 1]);});
}
test4();

 运行结果

Fatal error: Uncaught PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'votes' in 'field list' in D:\workspace\php\wj_test\illuminate_database\vendor\illuminate\database\Connection.php on line 712Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'votes' in 'field list' (SQL: update `userinfo` set `votes` = 1 where (`id` = 1)) in D:\workspace\php\wj_test\illuminate_database\vendor\illuminate\database\Connection.php on line 712Call Stack:0.0009     411368   1. {main}() D:\workspace\php\wj_test\illuminate_database\test.php:00.0208    1925160   2. test4() D:\workspace\php\wj_test\illuminate_database\test.php:1190.0208    1925480   3. Illuminate\Database\Capsule\Manager::transaction(class Closure) D:\workspace\php\wj_test\illuminate_database\test.php:1170.0208    1925856   4. Illuminate\Database\Capsule\Manager::__callStatic(string(11), array(1)) D:\workspace\php\wj_test\illuminate_database\test.php:1170.0269    2634512   5. Illuminate\Database\MySqlConnection->transaction(class Closure, ???) D:\workspace\php\wj_test\illuminate_database\vendor\illuminate\database\Capsule\Manager.php:2000.0705    3895296   6. Illuminate\Database\MySqlConnection->handleTransactionException(class Illuminate\Database\QueryException, long, long) D:\workspace\php\wj_test\illuminate_database\vendor\illuminate\database\Concerns\ManagesTransactions.php:37

此时update执行Illuminate\Database\Connection::update(),update调用Connection::run()执行,run()通过Connection::runQueryCallback()执行,产生PDO异常,再将PDO异常传递给\Illuminate\Database\QueryException异常。

使用throw 会直接输出异常。

PDOException:PHP: PDOException - Manual

3.1.2 手动管理数据库事务

function test5()
{Capsule::beginTransaction();try {Capsule::table('userinfo')->where(['id' => 1])->update(['votes' => 1]);Capsule::commit();} catch (\Throwable $th) {var_dump($th->getMessage());Capsule::rollBack();}
}
test5();

 和之前是同样的道理,代码最后执行都是Connectionl类,Connectionl::beginTransaction()、Connectionl::commit()、Connectionl::rollback(),都是Connectionl中调用的ManagesTransactions类中的方法。

例子中Capsule类相当于官网的DB类。

四、构造器

参考

illuminate/database 使用 一-CSDN博客

Hyperf

自己写的博客有涉及一些运行原理,官网的例子比较多。

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/239579.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【数据结构】队列的使用|模拟实现|循环队列|双端队列|面试题

一、 队列(Queue) 1.1 概念 队列&#xff1a;只允许在一端进行插入数据操作&#xff0c;在另一端进行删除数据操作的特殊线性表&#xff0c;队列具有先进先出FIFO(First In First Out) 入队列&#xff1a;进行插入操作的一端称为队尾&#xff08;Tail/Rear&#xff09; 出队列…

Vue 初始化數組后操作另一個數組onMounted和watch

Vue 的父组件和子组件的生命周期钩子函数执行顺序可以归类为以下 4 部分&#xff1a; 1、加载渲染过程 父 beforeCreate -> 父 created -> 父 beforeMount -> 子 beforeCreate -> 子 created -> 子beforeMount -> 子 mounted -> 父 mounted 注意&#x…

深度剖析:Golang中结构体方法的高级应用

深度剖析&#xff1a;Golang中结构体方法的高级应用 引言结构体方法的基础回顾结构体的定义和用法方法的定义和绑定基本语法和用法 高级特性与应用封装、继承和多态方法集与接口的关系结构体方法的匿名字段和嵌入结构体 性能优化与最佳实践接收器类型的选择&#xff1a;指针还是…

文档 - - - Docsify文档创建

目录 1. Docsify 介绍2. 创建 Docsify 项目2.1 安装 Node.js2.1 安装 docsfiy-cli2.3 初始化项目2.4 运行项目2.5 使用 Python 运行项目&#xff08;扩展&#xff0c;不推荐有bug&#xff09; 3. 配置 Docsify 项目3.1 修改等待加载文字3.2 添加网站 ico 图标3.3 创建新页面写文…

Redux与React环境准备、实现counter(及传参)、异步获取数据

环境说明&#xff1a; 一&#xff1a;说明 在React中使用redux&#xff0c;官方要求安装两个其他插件&#xff1a;Redux Toolkit和react-redux 1. Redux ToolKit(RTK) - 官方推荐编写Redux逻辑的方式&#xff0c;是一套工具的集合集&#xff0c;简化书写方式 &#xff08;简化…

【数据结构之单链表】

数据结构学习笔记---003 数据结构之单链表1、什么是单链表?1.1、概念及结构 2、单链表接口的实现2.1、单链表的SList.h2.1.1、定义单链表的结点存储结构2.1.2、声明单链表各个接口的函数 2.2、单链表的SList.c2.2.1、遍历打印链表2.2.2、销毁单链表2.2.3、打印单链表元素2.2.4…

跨域问题的解决

1.什么是跨域&#xff1f; 浏览器从一个域名的网页去请求另外一个域名的资源时&#xff0c;域名、端口或者协议不同都是跨域 2.跨域的解决方案 设置CORS响应头∶后端可以在HTTP响应头中添加相关的CORS标头&#xff0c;允许特定的源&#xff08;域名、协议、端口)访问资源。S…

VM进行TCP/IP通信

OK就变成这样 vm充当服务端的话也是差不多的操作 点击连接 这里我把端口号换掉了因为可能被占用报错了&#xff0c;如果有报错可以尝试尝试换个端口号 注&#xff1a; 还有一个点在工作中要是充当服务器&#xff0c;要去网络这边看下他的ip地址 拉到最后面

【github】github设置项目为私有

点击setting change to private 无脑下一步

day6 力扣公共前缀--go实现---对字符串的一些思考

今日份知识&#xff1a; curl -x 指定方法名 请求的url -d 请求体body里面的内容 //curl命令 curl -x Get 127.0.0.1:8080/add/user -d jinlicurl如果不指定方法&#xff0c;默认使用get方法&#xff0c;在go里面&#xff0c;get方法到底可以不可以把内容数据写在body里面传…

web架构师编辑器内容-创建业务组件和编辑器基本行为

编辑器主要分为三部分&#xff0c;左侧是组件模板库&#xff0c;中间是画布区域&#xff0c;右侧是面板设置区域。 左侧是预设各种组件模板进行添加 中间是使用交互手段来更新元素的值 右侧是使用表单的方式来更新元素的值。 大致效果&#xff1a; 左侧组件模板库 最初的模板…

基于JSP+Servlet+Mysql的调查管理系统

基于JSPServletMysql的调查管理系统 一、系统介绍二、功能展示1.项目内容2.项目骨架3.数据库3.登录4.注册3.首页5.系统管理 四、其它1.其他系统实现五.获取源码 一、系统介绍 项目名称&#xff1a;基于JSPServlet的调查管理系统 项目架构&#xff1a;B/S架构 开发语言&#…

在Next.js和React中搭建Cesium项目

在Next.js和React中搭建Cesium项目&#xff0c;需要确保Cesium能够与服务端渲染(SSR)兼容&#xff0c;因为Next.js默认是SSR的。Cesium是一个基于WebGL的地理信息可视化库&#xff0c;通常用于在网页中展示三维地球或地图。下面是一个基本的步骤&#xff0c;用于在Next.js项目中…

群组推荐模型---SoAGREE(Social-Enhanced Attentive Group Recommendation)

SoAGREE 概要方法Hierarchical Attention Network LearningAttentive User Representation Learning NCF(Neural Collaborative Filtering) 概要 此论文是在AGREE(Attentive Group Recommendation)模型上的进一步增强&#xff0c;有兴趣的朋友可以去看上一篇博客讲述的就是AGR…

.raw 是一个 Anndata 包中的对象,用于存储原始的单细胞数据。scanpy种如何查看 .raw 对象的内容,

1查看 .raw 对象的内容&#xff0c;可以使用以下方法&#xff1a; .raw 是一个 Anndata 包中的对象&#xff0c;用于存储原始的单细胞数据。 使用 .X 属性查看原始数据矩阵&#xff1a;.raw.X 这将返回一个 Numpy 数组&#xff0c;其中包含原始数据的数值。 使用 .var_names 属…

nodejs微信小程序+python+PHP兴趣趣班预约管理系统设计与实现-计算机毕业设计推荐

目 录 摘 要 I ABSTRACT II 目 录 II 第1章 绪论 1 1.1背景及意义 1 1.2 国内外研究概况 1 1.3 研究的内容 1 第2章 相关技术 3 2.1 nodejs简介 4 2.2 express框架介绍 6 2.4 MySQL数据库 4 第3章 系统分析 5 3.1 需求分析 5 3.2 系统可行性分析 5 3.2.1技术可行性&#xff1a;…

ARM作业1

汇编实现三个灯闪烁 汇编代码&#xff1a; .text .global _start _start: 设置GPIOE,GPIOF时钟使能LDR R0,0X50000A28 LDR R1,[R0] ORR R1,R1,#(0x3<<4) STR R1,[R0] 设置PE10,PF10,PE8为输出 LED1LDR R0,0X50006000LDR R1,[R0]ORR R1,R1,#(0X1<<20)BIC R1…

力扣每日一题day38[106. 从中序与后序遍历序列构造二叉树]

给定两个整数数组 inorder 和 postorder &#xff0c;其中 inorder 是二叉树的中序遍历&#xff0c; postorder 是同一棵树的后序遍历&#xff0c;请你构造并返回这颗 二叉树 。 示例 1: 输入&#xff1a;inorder [9,3,15,20,7], postorder [9,15,7,20,3] 输出&#xff1a;[…

华为鸿蒙(HarmonyOS):连接一切,智慧无限

华为鸿蒙是一款全场景、分布式操作系统&#xff0c;旨在构建一个真正统一的硬件生态系统。该操作系统于2019年8月首次发布&#xff0c;并被设计为可以应用于各种设备&#xff0c;包括智能手机、智能手表、智能电视、车载系统等多种智能设备。 推荐一套最新版的鸿蒙4.0开发教程 …

从零开发短视频电商 在AWS上SageMaker部署模型自定义日志输入和输出示例

从零开发短视频电商 在AWS上SageMaker部署模型自定义日志输入和输出示例 怎么部署自定义模型请看&#xff1a;从零开发短视频电商 在AWS上用SageMaker部署自定义模型 都是huaggingface上的模型或者fine-tune后的。 为了适配jumpstart上部署的模型的http输入输出&#xff0c;我…