在 cakephp 3 中动态更改数据库连接

Dynamically change database connection in cakephp 3

我正在尝试即时更改 cakephp 3 中使用的数据库连接。我找到的这个问题的每个答案都指的是 cakephp 2 (These three for instance).

找到了 cakephp 3 数据库数量有限的解决方案,并具体定义了哪个 Table 文件将使用哪个数据库。

问题是我想为每个新用户创建一个新数据库,并在他登录时更改为他的数据库。我无法提前知道所有将存在的数据库,将其写在config/app.php 个文件。

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

使用 ConnectionManager::config() 函数即时创建连接,使用 ConnnectionManager::alias() 方法让所有 Table 类 默认使用它。

这里有一篇很好的文章描述了这个过程:

http://mark-story.com/posts/view/using-cakephp-and-a-horizontally-sharded-database

唯一的区别是您可以即时创建连接配置,而不是像那篇文章中那样手动声明分片。

更改一个模型的数据库连接:

在app.php中:

'test' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => MySQL_HOST,
            //'port' => 'nonstandard_port_number',
            'port' => MySQL_PORT,
            'username' => MySQL_USER,
            'password' => MySQL_PASS,
            'database' => 'test',
            'encoding' => 'utf8',
            'timezone' => 'UTC',
            'cacheMetadata' => true,
            'quoteIdentifiers' => false,
            'log' => false,
        //'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
        ]

在控制器中:

$conn = ConnectionManager::get('test');
 $_model = TableRegistry::get('your_alias', ['table' => 'your_table', 'connection' => $conn]);
 
         

Configuring table connections

 namespace App\Model\Table;

 use Cake\ORM\Table;

 class ArticlesTable extends Table
 {
     public static function defaultConnectionName() {
     return 'replica_db';
     }
 }