chriss
chriss

Reputation: 340

CakePHP3 Changing Database Connections in Plugins

I have problems with switching a database connection in CakePHP3.

I would like to change the database connection (based on a subdomain, MultiTenant system). But I would like to outsource this connection-change to a plugin. For this I wrote a small plugin (MTA) with a middleware class, with the following invoke function:

    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;
    }

That does not work. Maybe it is already too late to change the connection or set up an alias.

Is there still a possibility to change the connections for all models in a plugin, or do I have to do this earlier (for example in bootstrap.php)?

Upvotes: 1

Views: 154

Answers (1)

ndm
ndm

Reputation: 60503

That should work fine for all tables that are being instantiated after that point, however you need to move the $next() call (which invokes the next middlware in the queue) to the end of the method, otherwise your code will run after the application request has been completed.

Upvotes: 1

Related Questions