Dynamic Model Binding in CakePHP

One topic in CakePHP that took some time to wrap our heads around was binding to a model dynamically – that is, if you’re working in a Controller and would like to access another Model without registering the Model in the $uses array (exposing the model to the entire Controller). On occasion, this can be a handy snippet – for example in a switch statement where you’re segregating calls to different Models based on a certain criteria.

switch ($type)
{
    case 0:
        $model = 'FinanceNews';
        break;
    case 1:
        $model = 'SportsNews';
        break;
    case 2:
        $model = 'LocalNews';
        break;
}
 
App::Import('Model', $model);
$this->DynamicModel = new $model;
 
$conditions = array(
        'conditions'=> array($model.'.published' => 1),
        'fields'=> array($model.'.id',$model.'.title',$model.'.news_date'),
        'order' => $model.'.news_date DESC',
        'limit' => 10
        );
 
$this->DynamicModel->find('all', $conditions);