content top
Dynamically Loading a model in Cake PHP

Dynamically Loading a model in Cake PHP

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.

1. Controller::loadModel();

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

2. ClassRegistry::init()

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

3. App:import()

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.

Blog Widget by LinkWithin

2 Comments »

  1. avatar comment-top

    Thank You Robin. I am new to cake and was searching a while for this. Thank you for this post.

    comment-bottom
  2. avatar comment-top

    Thanks.
    I was looking for how load model from model in cakePHP. It works! :)

    comment-bottom

RSS feed for comments on this post. TrackBack URL

Leave a comment