CakePHP 2 – Dynamically Globally Changing the Database Connection

Written by James McDonald

January 25, 2017

Dynamically Globally Changing the Database Connection in CakePHP 2.x

I use this code in app/Model/AppModel.php to dynamically change my database environment in CakePHP 2.x depending where it is running

<?php
//app/Model/AppModel.php
App::uses('Model', 'Model');
App::uses( 'ConnectionManager', 'Model');

class AppModel extends Model {
    
    public $useDbConfig = 'default';
    
    function __construct(){
        parent::__construct();
        
        $env = getenv('ENVIRONMENT') ?: 'HOME';
        
        // normally settings in Config/settings.php and
        // read with Configure but shown inline for clarity
        // $db_connections = Configure::read('datasources')
        $db_connections =  [
                                'HOME' => 'homeTestDB', // my laptop
                                'TEST' => 'prodTestDB', 
                                'LIVE' => 'prodLiveDB' 
                           ];

        $db_connection = $db_connections[$env];
        
        if ($db_connection){
            $this->useDbConfig = $db_connection;
        }
        
        
    } 


    function db_config(){
        
                $dataSource = ConnectionManager::getDataSource($this->useDbConfig);
                return [ 
                    'database' => $dataSource->config['database'],
                    'config' => $this->useDbConfig,
                    'host' => $dataSource->config['host']
                        ];
                
    }
    
}

You put a the following in your .htaccess file which sets the ENVIRONMENT to HOME

SetEnv ENVIRONMENT HOME
Unfortunate problem when running from the cake command shell

However when running programs from the cake shell you get this nasty error:

Error: Table app_models for model AppModel was not found in datasource homeTestDB.
#0 /path/to/my/cake/install/vendors/cakephp/cakephp/lib/Cake/Model/Model.php(3667): Model->setSource('app_models')

 

I thought the the fix was to add a line of code to tell cake that AppModel doesn’t reference a table, BUT THIS DOESN’T WORK

class AppModel extends Model {
    
    public $useDbConfig = 'default';
    // add the following
    public $useTable = false;

    //... rest of code

However after installing the CakePHP plugin to my Netbeans IDE I found that when I typed in __construct it gave me two options…

The default __construct magic method:

<?php

    public function __construct(){
    }

And also a CakePHP method __construct method inherited from the vendors/cakephp/cakephp/lib/Cake/Model/Model.php so I now changed it to the following and no longer have the command line error

<?php

class AppModel extends Model {
    
    public function __construct($id = false, $table = null, $ds = null) {
        parent::__construct($id, $table, $ds);
        
         $env = getenv('ENVIRONMENT') ?: 'RUNTESTS';

        $db_connections = Configure::read('datasources');
        
        $db_connection = $db_connections[$env];
        
        if ($db_connection){
            $this->useDbConfig = $db_connection;
        }
        
    }

Refshttps://jamesmcdonald.id.au/it-tips/globally-change-the-default-database-connection-in-cakephp

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

You May Also Like…