illuminate/database 使用 四

文档:Hyperf

Database: Getting Started - Laravel 10.x - The PHP Framework For Web Artisans

因为hyperf使用illuminate/database,所以按照文章,看illuminate/database代码实现。

一、读写分离

根据文档读写的host可以分开。设置读写分离的前提,做数据库出从同步。
 

1.1 数据库主从同步

参考:mysql5.7 主从配置-CSDN博客

1.2 设置

配置中设置三个数据read、write、sticky。read、write都包含host数组,其配置会和主要配置合并。就是说,比如host相同,应该在read、write中设置对应数据,以覆盖主要设置。

sticky选项是一个可选值,可用于允许在当前请求周期内立即读取已写入数据库的记录。如果启用了sticky选项,并且在当前请求周期中对数据库执行了“写”操作,则任何进一步的“读”操作都将使用“写”连接。这确保了在请求周期内写入的任何数据都可以在同一请求期间立即从数据库中读回。

源码如下:

#Illuminate\Database\Connectors\ConnectionFactory
protected function getReadConfig(array $config){return $this->mergeReadWriteConfig($config, $this->getReadWriteConfig($config, 'read'));}
protected function getWriteConfig(array $config){return $this->mergeReadWriteConfig($config, $this->getReadWriteConfig($config, 'write'));}
protected function mergeReadWriteConfig(array $config, array $merge){return Arr::except(array_merge($config, $merge), ['read', 'write']);}#Illuminate\Database\Connection
public function getReadPdo(){if ($this->transactions > 0) {return $this->getPdo();}if ($this->readOnWriteConnection ||($this->recordsModified && $this->getConfig('sticky'))) {return $this->getPdo();}if ($this->readPdo instanceof Closure) {return $this->readPdo = call_user_func($this->readPdo);}return $this->readPdo ?: $this->getPdo();}

1.3 测试

配置如下

#config/database.php
return ['migrations' => '', //数据迁移//PDO文档 https://www.php.net/manual/zh/pdo.constants.php'default' => 'master','connections' => ['master' => ['driver' => 'mysql','host' => 'localhost','database' => 'test','username' => 'root','password' => 'qwe110110','charset' => 'utf8','collation' => 'utf8_general_ci','prefix' => '','port' => '3306','read' => ['host' => ['127.0.0.1'],'port' => '3307',],'write' => ['host' => ['127.0.0.1'],'port' => '3306',],],]
];

 测试代码

function test1()
{new App();$query = "concat('-',id)";$as = "id";//$info1 = DbManager::table('userinfo')->select(['name'])->selectSub($query, $as)->addSelect(['age'])->get();$info1 = DbManager::table('userinfo')->select(['name'])->selectSub($query, $as)->addSelect(['age'])->get();var_dump($info1);$data = $info1->all();$insertData = ['name' => 'test1', 'age' => 1];$id = DbManager::table('userinfo')->insertGetId($insertData);var_dump($id);//exit;//$sql = "CONCAT('A-',name)";//$info2 = DbManager::table('userinfo')->selectSub($sql, "table")->toSql()->dump();
}
test1();

 返回结果

string(29) "Illuminate\Support\Collection"
array(8) {[0] =>class stdClass#18 (3) {public $name =>string(3) "123"public $id =>string(2) "-1"public $age =>int(22)}[1] =>class stdClass#22 (3) {public $name =>string(5) "name2"public $id =>string(2) "-2"public $age =>int(13)}[2] =>class stdClass#23 (3) {public $name =>string(5) "name3"public $id =>string(2) "-3"public $age =>int(24)}[3] =>class stdClass#24 (3) {public $name =>string(5) "33321"public $id =>string(2) "-4"public $age =>int(0)}[4] =>class stdClass#25 (3) {public $name =>string(5) "test1"public $id =>string(2) "-5"public $age =>int(1)}[5] =>class stdClass#26 (3) {public $name =>string(5) "test1"public $id =>string(2) "-6"public $age =>int(1)}[6] =>class stdClass#27 (3) {public $name =>string(5) "test1"public $id =>string(2) "-7"public $age =>int(1)}[7] =>class stdClass#28 (3) {public $name =>string(5) "test1"public $id =>string(2) "-8"public $age =>int(1)}
}
int(9)

 从库:

 主库

 

 测试成功~

1.4 返回数据处理

从测试结果看,返回的都是对象,因为默认使用PDO::FETCH_OBJ。

参考:PHP: PDO - Manual

源码如下

#Illuminate\Database\Capsule\Manager
public function __construct(Container $container = null){$this->setupContainer($container ?: new Container);// Once we have the container setup, we will setup the default configuration// options in the container "config" binding. This will make the database// manager work correctly out of the box without extreme configuration.$this->setupDefaultConfiguration();$this->setupManager();}
protected function setupDefaultConfiguration(){$this->container['config']['database.fetch'] = PDO::FETCH_OBJ;$this->container['config']['database.default'] = 'default';}
public function setFetchMode($fetchMode){$this->container['config']['database.fetch'] = $fetchMode;return $this;}#Illuminate\Database\Connection
protected $fetchMode = PDO::FETCH_OBJ;
public function select($query, $bindings = [], $useReadPdo = true){return $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) {if ($this->pretending()) {return [];}// For select statements, we'll simply execute the query and return an array// of the database result set. Each element in the array will be a single// row from the database table, and will either be an array or objects.$statement = $this->prepared($this->getPdoForSelect($useReadPdo)->prepare($query));$this->bindValues($statement, $this->prepareBindings($bindings));$statement->execute();return $statement->fetchAll();});}
protected function prepared(PDOStatement $statement){$statement->setFetchMode($this->fetchMode);$this->event(new StatementPrepared($this, $statement));return $statement;}

想返回数组可以设置为PDO::FETCH_ASSOC。最简单的方法就是替换源码,二次开发最好就是用对象,或者写个对象转数组的方法,tp里面有源码。tp是查出来对象,可使用toArray()搞成数组。

get()返回的类是Illuminate\Support\Collection,此类中还有一些数据统计的方法,比如平均值之类。意思就是查出来数据再做数据统计。

二、多库配置

根据laravel文档:如果应用程序在config/database.php配置文件中定义了多个连接,则可以通过DB facade提供的连接方法访问每个连接。

use Illuminate\Support\Facades\DB;$users = DB::connection('sqlite')->select(/* ... */);
$pdo = DB::connection()->getPdo();

但是仅用这个库由于没有对应数据,会返回db类是null。

源码如下:

#Illuminate\Support\Facades\Facade
public static function getFacadeRoot(){return static::resolveFacadeInstance(static::getFacadeAccessor());}
public static function __callStatic($method, $args){$instance = static::getFacadeRoot();if (!$instance) {throw new RuntimeException('A facade root has not been set.');}return $instance->$method(...$args);}protected static function resolveFacadeInstance($name){if (is_object($name)) {return $name;}if (isset(static::$resolvedInstance[$name])) {return static::$resolvedInstance[$name];}if (static::$app) {return static::$resolvedInstance[$name] = static::$app[$name];}}

根据方法resolveFacadeInstance(),$name应该是‘db’,不是对象,$resolvedInstance、$app没有对应对象,所以返回空。估计得配合其他类库。比如hyperf中需要

composer require hyperf/database

 那么不用其他类库怎么实现多库切换……

多库配置

return ['migrations' => '', //数据迁移//PDO文档 https://www.php.net/manual/zh/pdo.constants.php'default' => 'master','connections' => ['master' => ['driver' => 'mysql','host' => 'localhost','database' => 'test','username' => 'root','password' => 'mima','charset' => 'utf8','collation' => 'utf8_general_ci','prefix' => '','port' => '3306','read' => ['host' => ['127.0.0.1'],'port' => '3307',],'write' => ['host' => ['127.0.0.1'],'port' => '3306',],],'test' => ["driver" => "mysql","host" => "127.0.0.1","database" => "test1","username" => "root","password" => "mima",'charset' => 'utf8mb4','collation' => 'utf8mb4_unicode_ci','prefix' => '','port' => '3307',],],
];
function test2()
{$app = new App();$info = DbManager::connection('test')->table('userinfo')->where('id', '=', 1)->get();$info = $info->first();var_dump($info);
}test2();

 返回数据

class stdClass#20 (2) {public $id =>int(1)public $name =>string(1) "1"
}

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

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

相关文章

系列十六、Spring IOC容器的扩展点

一、概述 Spring IOC容器的扩展点是指在IOC加载的过程中,如何对即将要创建的bean进行扩展。 二、扩展点 2.1、BeanDefinitionRegistryPostProcessor 2.1.1、概述 BeanDefinitionRegistryPostProcessor是bean定义的后置处理器,在BeanDefinition加载后&a…

142.【Nginx负载均衡-01】

Nginx_基础篇 (一)、Nginx 简介1.背景介绍(1).http和三大邮局协议(2).反向代理与正向代理 2.常见服务器对比(1).公司介绍(2).lls 服务器(3).Tomcat 服务器(4).Apache 服务器(5).Lighttpd 服务器(6).其他的服务器 3.Nginx的优点(1).速度更快、并发更高(2).配置简单,扩…

力扣:提莫攻击

代码&#xff1a; class Solution { public:int findPoisonedDuration(vector<int>& timeSeries, int duration){//根据数组中给出的元素的值来进行判断&#xff01;//若后面元素-前面元素>d 中了d秒&#xff01;// <d 中了差的秒数&…

从0到0.01入门 Webpack| 008.精选 Webpack面试题

&#x1f90d; 前端开发工程师&#xff08;主业&#xff09;、技术博主&#xff08;副业&#xff09;、已过CET6 &#x1f368; 阿珊和她的猫_CSDN个人主页 &#x1f560; 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 &#x1f35a; 蓝桥云课签约作者、已在蓝桥云…

常见位运算的详讲!

今日为大家详细讲解一番关于常见位运算的操作&#xff0c;本文主要介绍一些位运算的操作符&#xff0c;然后再通过简单->中等->困难的例题&#xff0c;让大家彻底搞懂关于位运算的知识&#xff01; 位运算的介绍&#xff01; 1.基础位运算 ">>"右移操作…

WebGL/threeJS面试题扫描与总结

什么是 WebGL&#xff1f;什么是 Three.js&#xff1f;请解释three.js中的WebGL和Canvas的区别&#xff1f; WebGL(全写Web Graphics Library)是一种3D绘图协议&#xff0c;这种绘图技术标准允许把JavaScript和OpenGL ES 2.0结合在一起&#xff0c;通过增加OpenGL ES 2.0的一个…

Cortex-M与RISC-V区别

环境 Cortex-M以STM32H750为代表&#xff0c;RISC-V以芯来为代表 RTOS版本为RT-Thread 4.1.1 寄存器 RISC-V 常用汇编 RISC-V 关于STORE x4, 4(sp)这种寄存器前面带数字的写法&#xff0c;其意思为将x4的值存入sp4这个地址&#xff0c;即前面的数字表示偏移的意思 反之LOA…

MySQL 库操作 | 表操作

文章目录 一.MySQL库的操作1.创建数据库2.字符集和校验规则3.操纵数据库 二.MySQL表的操作1.创建表2.操作表3.删除表 一.MySQL库的操作 1.创建数据库 创建数据库 创建数据库的SQL如下&#xff1a; CREATE DATABASE [IF NOT EXISTS] db_name [[DEFAULT] CHARSETcharset_name…

吉他初学者学习网站搭建系列(3)——如何实现吉他在线调音

文章目录 背景知识teoriapitchytone效果 背景知识 学过初中物理就会知道&#xff0c;声音是由空气振动产生的。振动产生波&#xff0c;所以声音就是不同振幅和频率的波构成的。振幅决定了声音的响度&#xff0c;频率决定了声音的音高。想更进一步了解的可以访问这个网页wavefo…

嵌入式的学习需要合理规划时间

低级的欲望放纵即可获得&#xff0c;高级的欲望只有克制才能达成。——卡耐基1、粉丝的误会 很多粉丝&#xff0c;问我&#xff0c; "胡老师我想报您的培训班。" ... 得知我知识业余时间写文章&#xff0c;紧接着又会问&#xff0c; "jg单位这么清闲啊&#…

基于uniapp+vue微信小程序的健康饮食管理系统 907m6

设计这个微信小程序系统能使用户实现不需出门就可以在手机或电脑前进行网上查询美食信息、 运动视频等功能。 本系统由用户和管理员两大模块组成。用户界面显示在应用程序中&#xff0c;管理员界面显示在后台服务中&#xff0c;通过小程序端与服务端间进行数据交互与数据传输实…

4G执法记录仪在大型安保集团,保安集团、蓝天救援队中的 应用,行为规范化,人员定位,考勤打卡,应急指挥调度

【智能化升级】揭秘4G/5G执法记录仪在安保与救援领域如何重塑行业标准与效率 在快速发展的社会当中&#xff0c;大型安保集团、保安集团和蓝天救援队所肩负的任务日益繁重与复杂。无论是在平时的治安巡查、安保执勤&#xff0c;还是在突发公共事件的应急响应中&#xff0c;如何…