hyperf 三十一 极简DB组件

server/2024/9/24 7:25:48/

一 安装及配置

composer require hyperf/db
php bin/hyperf.php vendor:publish hyperf/db

默认配置 config/autoload/db.php 如下,数据库支持多库配置,默认为 default

配置项类型默认值备注
driverstring数据库引擎 支持 pdomysql
hoststringlocalhost数据库地址
portint3306数据库地址
databasestring数据库默认 DB
usernamestring数据库用户名
passwordstringnull数据库密码
charsetstringutf8数据库编码
collationstringutf8_unicode_ci数据库编码
fetch_modeintPDO::FETCH_ASSOCPDO 查询结果集类型
pool.min_connectionsint1连接池内最少连接数
pool.max_connectionsint10连接池内最大连接数
pool.connect_timeoutfloat10.0连接等待超时时间
pool.wait_timeoutfloat3.0超时时间
pool.heartbeatint-1心跳
pool.max_idle_timefloat60.0最大闲置时间
optionsarrayPDO 配置

 具体接口可以查看 Hyperf\DB\ConnectionInterface

方法名返回值类型备注
beginTransactionvoid开启事务 支持事务嵌套
commitvoid提交事务 支持事务嵌套
rollBackvoid回滚事务 支持事务嵌套
insertint插入数据,返回主键 ID,非自增主键返回 0
executeint执行 SQL,返回受影响的行数
queryarray查询 SQL,返回结果集列表
fetcharray, object查询 SQL,返回结果集的首行数据
connectionself指定连接的数据库

二 使用

php">#使用 DB 实例
use Hyperf\Context\ApplicationContext;
use Hyperf\DB\DB;$db = ApplicationContext::getContainer()->get(DB::class);$res = $db->query('SELECT * FROM `user` WHERE gender = ?;', [1]);#使用静态方法
use Hyperf\DB\DB;$res = DB::query('SELECT * FROM `user` WHERE gender = ?;', [1]);#使用匿名函数自定义方法
#此种方式可以允许用户直接操作底层的 PDO 或者 MySQL,所以需要自己处理兼容问题
use Hyperf\DB\DB;$sql = 'SELECT * FROM `user` WHERE id = ?;';
$bindings = [2];
$mode = \PDO::FETCH_OBJ;
$res = DB::run(function (\PDO $pdo) use ($sql, $bindings, $mode) {$statement = $pdo->prepare($sql);$this->bindValues($statement, $bindings);$statement->execute();return $statement->fetchAll($mode);
});

三 测试

php">use Hyperf\DB\DB as AustereDb;
use Hyperf\Utils\ApplicationContext;public function testdb1() {$db = ApplicationContext::getContainer()->get(AustereDb::class);$res = $db->query('SELECT * FROM `push_recode` WHERE id = ?;', [1]);var_dump($res);$res = AustereDb::query('SELECT * FROM `push_recode` WHERE id = ?;', [1]);var_dump($res);$sql = 'SELECT * FROM `push_recode` WHERE id = ?;';$bindings = [1];$mode = \PDO::FETCH_NUM;$res = AustereDb::run(function (\PDO $pdo) use ($sql, $bindings, $mode) {$statement = $pdo->prepare($sql);$this->bindValues($statement, $bindings);$statement->execute();return $statement->fetchAll($mode);});var_dump($res);
}

 测试结果

php">array(1) {[0]=>array(4) {["id"]=>int(1)["is_push"]=>int(1)["push_time"]=>string(19) "2024-04-11 08:10:13"["created_at"]=>NULL}
}
array(1) {[0]=>array(4) {["id"]=>int(1)["is_push"]=>int(1)["push_time"]=>string(19) "2024-04-11 08:10:13"["created_at"]=>NULL}
}
array(1) {[0]=>array(4) {[0]=>int(1)[1]=>int(1)[2]=>string(19) "2024-04-11 08:10:13"[3]=>NULL}
}

可能由于版本问题,Hyperf\Context\ApplicationContext类不存在,所以使用Hyperf\Utils\ApplicationContext。

使用三种方法查询数据,使用DB实例、使用静态方法、使用PDO。

四 原理

获取容器参考hyperf console 执行-CSDN博客。

数据库配置获取参考hyperf console 执行-CSDN博客

php bin/hyperf.php vendor:publish hyperf/db 创建配置文件config\autoload\db.php后,其中使用.env文件。所以若项目数据库在.env中设置,配置文件可以不用改。

使用静态方法也是先获取容器,再调用对应方法。

使用run方法是根据配置文件获取数据库连接驱动,获取对应链接,默认是pdo。

若驱动为mysql,实际运行Hyperf\DB\MySQLConnection::run(Closure $closure)。

Closure类为一个闭包。

五 源码

php">#config\autoload\db.php
return ['default' => ['driver' => 'pdo','host' => env('DB_HOST', 'localhost'),'port' => env('DB_PORT', 3306),'database' => env('DB_DATABASE', 'hyperf'),'username' => env('DB_USERNAME', 'root'),'password' => env('DB_PASSWORD', ''),'charset' => env('DB_CHARSET', 'utf8mb4'),'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),'fetch_mode' => PDO::FETCH_ASSOC,'pool' => ['min_connections' => 1,'max_connections' => 10,'connect_timeout' => 10.0,'wait_timeout' => 3.0,'heartbeat' => -1,'max_idle_time' => (float) env('DB_MAX_IDLE_TIME', 60),],'options' => [PDO::ATTR_CASE => PDO::CASE_NATURAL,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,PDO::ATTR_STRINGIFY_FETCHES => false,PDO::ATTR_EMULATE_PREPARES => false,],],
];
php">#Hyperf\DB\DBprotected $poolName;public function __construct(PoolFactory $factory, string $poolName = 'default'){$this->factory = $factory;$this->poolName = $poolName;}public static function __callStatic($name, $arguments){$container = ApplicationContext::getContainer();$db = $container->get(static::class);return $db->{$name}(...$arguments);}public function __call($name, $arguments){$hasContextConnection = Context::has($this->getContextKey());$connection = $this->getConnection($hasContextConnection);try {$connection = $connection->getConnection();$result = $connection->{$name}(...$arguments);} catch (Throwable $exception) {$result = $connection->retry($exception, $name, $arguments);} finally {if (! $hasContextConnection) {if ($this->shouldUseSameConnection($name)) {// Should storage the connection to coroutine context, then use defer() to release the connection.Context::set($contextKey = $this->getContextKey(), $connection);defer(function () use ($connection, $contextKey) {Context::set($contextKey, null);$connection->release();});} else {// Release the connection after command executed.$connection->release();}}}return $result;}private function getContextKey(): string{return sprintf('db.connection.%s', $this->poolName);}protected function getConnection(bool $hasContextConnection): AbstractConnection{$connection = null;if ($hasContextConnection) {$connection = Context::get($this->getContextKey());}if (! $connection instanceof AbstractConnection) {$pool = $this->factory->getPool($this->poolName);$connection = $pool->get();}return $connection;}
php">#Hyperf\DB\Pool\PoolFactoryprotected $container;public function __construct(ContainerInterface $container){$this->container = $container;}public function getPool(string $name){if (isset($this->pools[$name])) {return $this->pools[$name];}$config = $this->container->get(ConfigInterface::class);$driver = $config->get(sprintf('db.%s.driver', $name), 'pdo');$class = $this->getPoolName($driver);$pool = make($class, [$this->container, $name]);if (! $pool instanceof Pool) {throw new InvalidDriverException(sprintf('Driver %s is not invalid.', $driver));}return $this->pools[$name] = $pool;}protected function getPoolName(string $driver){switch (strtolower($driver)) {case 'mysql':return MySQLPool::class;case 'pdo':return PDOPool::class;}if (class_exists($driver)) {return $driver;}throw new DriverNotFoundException(sprintf('Driver %s is not found.', $driver));}
php">#Hyperf\DB\Pool\MySQLPoolprotected function createConnection(): ConnectionInterface{return new MySQLConnection($this->container, $this, $this->config);}

http://www.ppmy.cn/server/13885.html

相关文章

MongoDB磁盘空间占满,导致数据库被锁定,如何清理数据和磁盘空间

一、问题 1、我在实际项目中,遇到一个问题,随着数据每天的不断增加,导致mongodb的磁盘空间站满了,数据库被锁了,无法使用。 2、故障表现 部署的应用程序突然无法将数据写入数据库,但是可以正常读取数据。…

vue+springboot实验个人信息,修改密码,忘记密码功能实现

前端部分 新增Person(个人页面),Password(修改密码页面),还需要对Manager,login页面进行修改 router文件夹下的index.js: import Vue from vue import VueRouter from vue-router i…

JEECG表格选中状态怎么去掉

官网代码(在取消选中状态的时候不生效) rowSelection() {return {onChange: (selectedRowKeys, selectedRows) > {console.log(selectedRowKeys: ${selectedRowKeys}, selectedRows: , selectedRows);},getCheckboxProps: record > ({props: {disa…

编译原理 LR(0)

讲解视频:编译原理LR(0)分析表(上)_哔哩哔哩_bilibili 【编译原理】LR(0)分析表分析输入串_哔哩哔哩_bilibili 拓广文法 已知G:S->(S)S | ε 拓广文法: S -> S S -> (S)S S -> ε…

Java之二维数组

使用二维数组: 引用二维数组元素需要指明行下标和列下标。二维数组有两个指标,行数使用“数组名.length",每行的列数使用“数组名[i].length”。遍历是二维数组的基本算法,使用双重循环遍历二维数组。外层循环控制行,内存循环…

设计模式之模板方法模式详解(上)

模板方法模式 1)概述 1.定义 定义一个操作中算法的框架,而将一些步骤延迟到子类中,模板方法模式使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。 2.方案 背景:某个方法的实现需要多个步骤(类似…

Ribbon 添加右侧区域菜单项

效果图如下所示: 类似与上图效果所示,代码如下: RibbonPage* pageHome1 ribbonBar()->addPage(tr("Home")); //实现代码: { QMenu* menuOptions ribbonBar()->addMenu(tr("Options"))…