How to let Cakephp 3 choose database connection by

2019-07-09 05:00发布

问题:

I'm working with cakephp v3 and want to install the application in two different environments, one for development and one for production use. Both installations should consist of exactly the same files (and file contents), so I could use 'git' or 'svn' to easily deploy the application.

If both environments are hosted on the same machine, I need different database settings (so that the development env uses its own 'testing' DB). I thought of configuring two 'Datasources' in app.php, the 'default' one for production and a `development'.

But how can I switch between both sources?

To be more specific: Currently I define the following environment variable in my Apache config for the development environment:

SetEnv CAKEPHP_DEBUG 1

Then I changed the definition of 'debug' in the app.php file like this:

'debug' => (bool)getenv('CAKEPHP_DEBUG'),

This enables DEBUG mode only on the development machine. Now I also want to switch database configuration in the same easy way.

(I already found some solutions for cakephp v2, but all of them are pretty old and I'm not sure what's the best way to do it in cakephp v3.)

回答1:

The manual says

You can define as many connections as you want in your configuration file. You can also define additional connections at runtime using Cake\Datasource\ConnectionManager::config().

So I guess you can check the value of debug in AppController beforeFilter and change the default database connection

AppController.php

if(Configure::read('debug') == 1)
{
    ConnectionManager::config('default', [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'dev_server',
        'username' => 'dev_username',
        'password' => 'dev_passwd',
        'database' => 'development',
        'encoding' => 'utf8',
        'timezone' => 'UTC',
        'cacheMetadata' => true,
    ]);
}

I think you can do something similar in app.php using the ternary operator

app.php

'Datasources' => [
    'default' => getenv('CAKEPHP_DEBUG')== 1 ? [ /* debug params */ ] : [ /* default params */]
    ...
]

But somehow it don't seem the 'clean' way to do it

I think that a cleaner way would be to set both configurations in app.php and then in appController choose what configurations to use

app.php

'Datasources' => [
    'debug' => [ /* debug params */ ],
    'default' => [ /* default params */]
]

Table file

public static function defaultConnectionName() {
    if(Configure::read('debug') == 1)
        return 'debug';
    return 'default';
}