CakePHP3 在插件中更改数据库连接

CakePHP3 Changing Database Connections in Plugins

我在 CakePHP3 中切换数据库连接时遇到问题。

我想更改数据库连接(基于子域,MultiTenant 系统)。但我想将此连接更改外包给插件。 为此,我写了一个带有中间件 class 的小插件 (MTA),具有以下调用函数:

    public function __invoke($request, $response, $next)
    {
        $response = $next($request, $response);
        $tenantMap = TableRegistry::get('TenantMappings');
        $mapping = $tenantMap->findByName($request->subdomains()[0])->firstOrFail();
        ConnectionManager::config("alias_".$request->subdomains()[0], [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'username' => '***username***',
            'password' => '***password***',
            'database' => '***database***',
            'encoding' => 'utf8',
            'timezone' => 'UTC',
            'cacheMetadata' => true,
        ]); 
        ConnectionManager::alias ("alias_".$request->subdomains()[0], "default");
        Configure::write('Account.active', $mapping->account_id);


        return $response;
    }

那是行不通的。也许现在更改连接或设置别名已经太晚了。

是否还有可能更改插件中所有模型的连接,或者我是否必须提前进行此操作(例如在 bootstrap.php 中)?

对于在该点之后实例化的所有表,这应该可以正常工作,但是您需要将 $next() 调用(调用队列中的下一个中间件)移动到方法的末尾,否则您的代码将 运行 申请请求完成后。