1

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

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.

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

0

3 Answers 3

7

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-horizontally-sharded-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.

1
  • Based on Mark's article I added middleware (CakePHP 3) to create an alias based on form request data, effectively allowing a database change on the fly/at login - see gist.github.com/chopstik/…
    – chopstik
    Nov 13, 2019 at 10:01
1

Change database connection for one model:

In 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'],
        ]

In Controller :

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

0

Configuring table connections

 namespace App\Model\Table;

 use Cake\ORM\Table;

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.