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

3 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

  3. Many researchers emphasize the importance of accurate data sources in their studies, which is why they often cite reputable references. When referencing online information, it is essential to include proper links for credibility; for example, you can visit SOURCE for more details. Ensuring the reliability of your sources enhances the overall quality of your work. Proper citation practices are crucial in maintaining academic integrity.

    ReplyDelete