Banco de Dados Dinâmico e Multiplos em Cakephp

dezembro 7, 2017 em CakePhp, Php por Sândler

APLICAÇÃO NA CONFIG DATABASE

Os nomes dos bancos são definidos em:  /app/config/database.php

EXAMPLE Multibanco

public $pro = array(‘datasource’ => ‘Database/Mysql’,
‘persistent’ => false,
‘host’ => ’127.0.0.1′,
‘login’ => ‘root’,
‘password’ => ”,
‘database’ => ‘db_pro’,
‘encoding’ => ‘latin1′);

public $test = array(‘datasource’ => ‘Database/Mysql’,
‘persistent’ => false,
‘host’ => ’127.0.0.1′,
‘login’ => ‘root’,
‘password’ => ”,
‘database’ => ‘db_test’,
‘encoding’ => ‘latin1′);

function __construct()
 {
     $this->default = $this->pro;
     $localhost = explode( ':', $_SERVER['HTTP_HOST'] );
     $arrRequest = explode('/',$_SERVER['REQUEST_URI']);
     $nameController = ($localhost[0] == 'localhost')? $arrRequest[3] :$arrRequest[2];//PEGA CONTROLLER
     switch ($nameController) {
        case 'users':
        case 'profiles':
        case 'logs':
        case 'companies':
              $this->default = $this->pro;
        break;
        default:
              $this->default = $this->test; 
        break;
} 

 

 

 

APLICAÇÃO DA CONTROLLER OU MODEL

TESTE 1

So, inside your Model, you would use the useDbConfig Attribute:

classExampleextendsAppModel{public $useDbConfig ='test';}

Inside your Controller, simply use:

$this->ModelName->useDbConfig ='test';

Thats all.

TESTE 2

I would use Model::setDataSource() rather than just setting the database config var. This is because there are other possible changes that come with changing the datasource:

$this->Model->setDataSource('test');


Reference: https://book.cakephp.org/2.0/en/models/model-attributes.html