Configure the default Database Connection for the ENTIRE Application

I need to constantly change the databse in my development environment.

Now I do this:

'Datasources' => [
        'default' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'username' => 'hache',
            'password' => 'password',
            // 'database' => 'test_mail', // TEST
            'database' => 'hotelone', // HOTEL 1
            // 'database' => 'anotherone', // HOTEL 2
            // 'database' => 'onedatabase', // APARTHOTEL 30
            // 'database' => 'differentone', // HUGE ONE TEST
            'encoding' => 'utf8',
            'timezone' => 'UTC',

I just comment/uncomment the ‘database’ key.

The problem doing this is that if I modify some field/table and want to do a migration, the plugin will just create a schema-dump-default.lock and this casuses a lot of problems.

This is an expected behavior because I should do this:

    'Datasources' => [
        'default' => [
            'database' => 'hotelone', // HOTEL 1
        'demoroomclic' => [
            'anotherone' => 'demoroomclic', // HOTEL 2

If I define one Datasource per database, the migrations plugin will create differente dump files, one for each datasource.

The problem is that I can’t find the propper way to select a datasource as default Application-wide.

I mean, to select one on bootstrap.php and use it as the default one.

In the documentation I only find:

  • how to select them on the fly inside a script (and then, it returns to the default one) here
  • or to select one in each Table file here

So my question is:
Is there a way to make Cake use a different Datasource FOR ALL QUERIES other than ‘default’ as default?


The ‘default’ datasource will always be used by default. If you want to use another datasource, just need to configure another one and call in runtime.

Connection aliasing is what you need: Class ConnectionManager | CakePHP 4.2.

So for your use case don’t configure any default connection and later when bootstrapping the app alias the required connection as default.

1 Like