Saturday, April 3, 2010

Load model dynamically in CakePHP

Sometimes I may need a model that's only going to be used in an action, not the whole controller to lighten the load. Or in that rare occasion when I have to load a model that's not what the controller meant to work with.

I've used this for quite a while now, based on discussion in CakePHP mailing list here.

1. Controller::loadModel('yourmodel'); (preferred)

// in app/controllers/car_controllers.php
Controller::loadModel('Book');
$this->Book->find('all'); // the object initiated and added as a property to the controller, persistModel is enabled




or
2. ClassRegistry::init('yourmodel');

// in app/controllers/car_controllers.php
$book = ClassRegistry::init('Book'); // returns the object
$book->find('all');