Loading Models specific to certain actions
Friday, February 6th 2009, 3:55am
Topics: Tutorials, CakePHP
Tags: Model, Action, Cakephp
Views: 8,560, Comments: 7
Recently I was working on a project, where a certain controller had over 15ish+ different models. The problem is that each action needed a different model, and I didn't want to load all those models at once. By using my common sense, loading that many models would put more of a strain on load time by having to initialize each model and bind them to the controller. I needed a quick way to load a model(s) specific only to a certain action. At first I tried putting $this->user[] = array('Model'); at the top of each action, but that didn't work and it didn't initialize "before" the action like it is supposed to. So what I came up with is a little statement trick that you can place in your beforeFilter(), which will load models specific to certain actions. Enjoy!
Also it would be best to disable models be default in controller. This way it doesn't load a certain model twice, or overwrite the defaults.
/**
* Executed before each action
*/
function beforeFilter() {
parent::beforeFilter();
// Load action specific models
switch ($this->params['action']) {
case 'friends': $models = array('Friend'); break;
case 'messages': $models = array('Message'); break;
case 'blog': $models = array('Entry', 'Comment'); break;
}
if (!empty($models)) {
foreach ($models as $model) {
$this->loadModel($model);
}
}
}Also it would be best to disable models be default in controller. This way it doesn't load a certain model twice, or overwrite the defaults.
class TestController extends AppController {
var $uses = NULL;
}
7 Comments
kebza.cz
Feb 6th 2009, 04:13
www.milesj.me
Feb 6th 2009, 14:24
You can call ClassRegistry like you suggested, but I don't think it does what I just noted above.
blog.cakep...brasil.org
Mar 12th 2009, 04:23
www.milesj.me
Mar 12th 2009, 13:44
Mar 14th 2009, 10:22
how can you be sure that that the param passed corresponds to an existing model prior to make the classregistry/loadmodel ? if it doesnt exist the result is weird, so better don't reach to the execution ...
Maybe with file_exists can check if at least the Model file exist, but hard to check if the model is inside a plugin for example ...
Do you know any other way to check before try to load ?
JM
www.milesj.me
Mar 14th 2009, 13:19
Also loadModel() calls ClassRegistry::init(). The loadModel() checks to see if there is a cached model, if not it calls ClassRegistry. The ClassRegistry method will check if the model exists, if the model does not it will return the AppModel object.
Most of the logic checking is already existent, no need to do it again.
silantiev.com
May 4th 2009, 00:32