Dynamic Model Binding in CakePHP
Wayne Helman on May 17, 2009
2 Comments
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);
August 6th, 2010 @ 8:38 PM
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
August 8th, 2010 @ 3:11 PM
Could you post some code so we can have a look? Hard to say without seeing something.
Cheers.