Anuj TBE
Anuj TBE

Reputation: 9790

create a separate database config file in CakePHP 3

I'm using CakePHP 3.4

default database settings exists in config/app.php

I want to separate out or override database configuration outside app.php say in config/my_db.php and load it in bootstrap.php file.

This setting will now override default database setting that exists in app.php file.

Is there some way to do this ?

Edit 2

config/my.db.php file

<?php
return [
    'my_db' => [
       'Datasources' => [
           'default' => [
               'className' => 'Cake\Database\Connection',
               'driver' => 'Cake\Database\Driver\Mysql',
               'persistent' => false,
               'host' => 'localhost',
               'username' => 'root',
               'password' => 'my_pass',
               'database' => 'testdb',
               'encoding' => 'utf8',
               'timezone' => 'UTC',
               'flags' => [],
               'cacheMetadata' => true,
               'log' => false,
           ]
       ]
    ]
];

loading in bootstrap.php

Configure::load('my_db', 'default', false);

Upvotes: 0

Views: 1987

Answers (2)

  1. Create new file into folder config/
  2. Name it whatever you like: my_db.php
  3. Add your code configuration Code:

return [

        'my_db' => [
            'setting_1'   =>  'value_1',
            'setting_2'   =>  'value_2',
            'setting_3'   =>  'value_3',
        ],
    ];
  1. Now you have to load it. Open file config/bootstrap.php, locate line:

    Configure::load('app', 'default', false);

  2. and append this line underneath:

    Configure::load('my_db', 'default');

Try THis ::

config/bootstrap.php

Configure::load('my_app', 'default','false');

config/my_app.php

<?php

return [
       'Datasources' => [
           'default' => [
               'className' => 'Cake\Database\Connection',
               'driver' => 'Cake\Database\Driver\Mysql',
               'persistent' => false,
               'host' => 'localhost',
               'username' => 'root',
               'password' => 'my_pass',
               'database' => 'my_db',
               'encoding' => 'utf8',
               'timezone' => 'UTC',
               'flags' => [],
               'cacheMetadata' => true,
               'log' => false,
           ]
       ]
];

Upvotes: 1

ad_on_is
ad_on_is

Reputation: 1550

make a copy of your app.php, name it app_override.php and change your db-settings.

Then adapt your bootstrap.php like this

try {
    Configure::config('default', new PhpConfig());
    Configure::load('app', 'default', false);
} catch (\Exception $e) {
    exit($e->getMessage() . "\n");
}

Configure::load('app_override', 'default');

Upvotes: 0

Related Questions