在cakephp 3中动态更改数据库连接 [英] Dynamically change database connection in cakephp 3

查看:52
本文介绍了在cakephp 3中动态更改数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试即时更改 cakephp 3 中使用的数据库连接.我发现的该问题的每个答案都指向 cakephp 2 (三个 实例).

I'm trying to change the database connection used in cakephp 3 on the fly. Every answer to this question that I found refers to cakephp 2 (These three for instance).

这个家伙找到了针对 cakephp 3 的解决方案具有有限数量的数据库,并专门定义哪个Table文件将使用哪个数据库.

This guy found a solution for cakephp 3 having a finite number of databases, and specifically defining which Database would be used by which Table file.

问题是,我想为每个新用户创建一个新数据库,并在他登录时更改为他的数据库.我无法事先知道将存在的所有数据库,都必须将其写入文件.

The thing is that I want to create a new database for every new user, and change to his database when he logs in. I can't know in advance all the databases that will exist, to write it in the config/app.php file.

而且我无法在每个/src/Model/Table文件中设置默认数据库,因为每个数据库中的表都相同.

And I can't set the default database in each /src/Model/Table file, because the tables are the same in every database.

推荐答案

使用ConnectionManager::config()函数动态创建连接,并使用ConnnectionManager::alias()方法使所有Table类默认使用它.

Use the ConnectionManager::config() function to create connections on the fly and the ConnnectionManager::alias() method to make all your Table classes use it by default.

这里有一篇很好的文章介绍了该过程:

There is a very good article describing the process here:

http://mark-story. com/posts/view/using-cakephp-and-a-horizo​​ntallysharded-database

唯一的区别是您可以动态创建连接配置,而不是像该文章中所示那样手动声明分片.

The only difference is that you can create the connection config on the fly instead of declaring the shards manually as it was shown in that article.

这篇关于在cakephp 3中动态更改数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆