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');

2 comments:

  1. Load model dynamically in CakePHP | Source code bank11/4/10 9:04 AM

    [...] this article: Load model dynamically in CakePHP If you enjoyed this article please consider sharing [...]

    ReplyDelete
  2. Thanks this saved my life!But loadModel is kind of a bummer because you have to call it once for each model you want to load. It would be able to take a list of models.

    ReplyDelete