CakePHP 2 – Load model on the fly

1. Using loadModel

<?php App::uses('AppModel', 'Model'); 
class Foo extends AppModel { 
public $useTable = false; 
function __construct($tablen) { 
//first check table exists if(!check_table_exists($table)){ 
$this->useTable = 'comments_' . $tablename["id"];
}
parent::__construct();
}

function check_table_exists($table) {
$dbo = $this->getDataSource();

try {
$result = $dbo->execute('DESCRIBE ' . $table);
} catch (Exception $e) {
$result = false;
}
return $result;
}
}

$this->loadModel(‘Foo’, “footable”);

2. You can instantiate the model directly

$model_1 = new Model(array('table' => 'the_table', 'ds' => 'default'));
$model_2 = new Model(array('table' => 'the_table', 'ds' => 'database2'));

source: http://stackoverflow.com/questions/22514836/cakephp-load-model-on-the-fly-using-a-different-datasource

3. MISC.

A note on difference between app:import and loadmodel in CakePHP: http://www.devarticles.in/cakephp/a-note-on-difference-between-appimport-and-loadmodel-in-cakephp/

Using App::uses (instead of App::import) in a CakePHP: http://stackoverflow.com/questions/8994514/using-appuses-instead-of-appimport-in-a-cakephp-2-1-plugin

B logbook : PHP | Javascript | Laravel | CodeIgniter | VueJs | ReactJs | WordPress