You may need to access a different model in a controller that it actually belongs to. For example you may have to access the model ‘comment ‘ in a controller ‘Post”.
Or you may have to access the rating model inside you video Controller.
Following are three methods for using a different model in your controller.
This method actually calls ClassRegistry::init() and saves the instance of the model as a parameter in the controller.
Example:
Inside the controller class
$this->loadModel(’Comment’) ;
$this->Comment->delete(1);
Or
Controller::loadModel(’Comment’);
$comments = $this->Comment->find(’all’);
http://api.cakephp.org/class/controller#method-ControllerloadModel
This method creates an instance of the Model and returns it for use.
Example:
$comment = ClassRegistry::init(’Comment’);
$comments = $comment->find(’all’);
http://api.cakephp.org/class/class-registry#method-ClassRegistryinit
Calling App::import is equivalent to requiring the file.You need to create an instance of the class each time after you import the file.
http://book.cakephp.org/view/531/Importing-Controllers-Models-Components-Behaviors-
Example:
App::import(’Comment’);
$comment = new Comment();
$comments = $comment->find(’all’);
Which one is Best ?
The first method is prefereble over the latter two.
This is actually a basic thing in Cake PHP. But I am posting it for newbie like me.
RSS feed for comments on this post. TrackBack URL
November 29th, 2009 at 9:38 am
Thank You Robin. I am new to cake and was searching a while for this. Thank you for this post.
February 1st, 2010 at 8:10 pm
Thanks.
I was looking for how load model from model in cakePHP. It works!