PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 19, 2022

[FIXED] CakePHP3 Changing Database Connections in Plugins

 January 19, 2022     cakephp, cakephp-3.x, php     No comments   

Issue

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)?


Solution

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.



Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing