FiftyOneReasons

Interactive Media Development + Exploration

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);
Share the love:
  • Twitter
  • Digg
  • del.icio.us
  • Google Bookmarks
  • StumbleUpon
  • Technorati

Comments

Sergio

I having troubles using the var $uses. I want to use more than one model that aren’t associated with the model, and everything works fine, but only for the first model that is within the array of $uses, I see the array of the first model is giving me all the associations, but for the second model in the var uses isn’t returning me all the associations, only the table. Anyone know why is that??, I have two days trying this :(

Wayne Helman

Could you post some code so we can have a look? Hard to say without seeing something.

Cheers.


Leave Your Mark




Feel free to use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">