Cakephp 3中的动态数据源和全局?

时间:2017-02-23 23:33:47

标签: php cakephp controller connection cakephp-3.0

我有一个将被许多数据库使用的应用程序。要选择带有应用程序数据的数据库,我有一个带有连接参数的数据库(主机,用户名,密码,数据库......)

问题是这个动态创建的数据源不适用于应用程序的其余部分。

控制器代码

$data       = $this->request->data;
$connection = ConnectionManager::get("default");
$query      = "SELECT * FROM clients WHERE client_id = ".$data['codigo'];
$result     = $connection->execute($query)->fetchAll('assoc');

ConnectionManager::drop('default');            

$config = ConnectionManager::config('connection', [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => $result[0]['host'],
        'username' => $result[0]['username'],
        'password' => $result[0]['password'],
        'database' => $result[0]['database'],
        'encoding' => 'utf8',
        'timezone' => 'UTC',
        'flags' => [],
        'cacheMetadata' => true,
        'log' => false,
        'quoteIdentifiers' => false,
        'url' => env('DATABASE_URL', null),
    ]);

$connection = ConnectionManager::get('connection');
ConnectionManager::alias('connection', 'default');

return $this->redirect(['controller' => 'Mains', 'action' => 'index']);

在此重定向之后,显然其他控制器没有此数据源。

1 个答案:

答案 0 :(得分:0)

根据请求数据中的内容交换数据库当然有点不寻常 - 但通常需要在Cake的初始设置中更早地完成数据库连接,因为每个Controller的连接资源已经设置为default

如果您只是一次性交换,则可以在config/bootstrap.php(Cake通常设置它的ConnectionManager)中进行管理。

您无法访问$this->request,但可以从$ _REQUEST中获取,例如:

config/bootstrap.php中,更改以下行:

Cache::config(Configure::consume('Cache'));
ConnectionManager::config(Configure::consume('Datasources'));
Email::configTransport(Configure::consume('EmailTransport'));

对此:

Cache::config(Configure::consume('Cache'));

ConnectionManager::config(Configure::consume('Datasources'));
$connection = ConnectionManager::get("default");
$client = TableRegistry::get('Clients')->find()
    ->where(['client_id'=> $_REQUEST['client_id']])->firstOrFail();

ConnectionManager::drop('default');

$config = ConnectionManager::config('connection', [
    'className' => 'Cake\Database\Connection',
    'driver' => 'Cake\Database\Driver\Mysql',
    'persistent' => false,
    'host' => $client->host,
    'username' => $client->username,
    'password' => $client->password,
    'database' => $client->database,
    'encoding' => 'utf8',
    'timezone' => 'UTC',
    'flags' => [],
    'cacheMetadata' => true,
    'log' => false,
    'quoteIdentifiers' => false,
    'url' => env('DATABASE_URL', null),
]);

ConnectionManager::get('connection');

Email::configTransport(Configure::consume('EmailTransport'));

编辑:从原始SQL切换到Table :: find()