If knowledge is power, then sharing knowledge is ultimate powertrip
Latest Updates
You are here: Home >> Frameworks >> Cakephp >> Access model from controller

Access model from controller

Sometimes, or very rarely we might need to access model from controller or AppController (Application Controller). This could be for fetching values from a table and make it available for all the controllers in the application (AppController is inherited by all the other controllers). Also, often we need to access models that are not associated with a controller.

I faced this when I had to load some User Session values (which is stored in a database table) in my AppController (app_controller.php) to use with a custom Login process. I was actually integrating a single sign-on process in CakePHP with an external application.

The loadModel function came handy here. See the code below.

$this->loadModel(’UserSession’);
debug($this->UserSession->find(’all’));

By just calling the loadModel function and passing the Model name, the model now becomes available to the controller and we could perform any operations on that model.

By using loadModel, we can reduce the overhead of declaring model names in $uses variable.

About Jawed Shamshedi

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Scroll To Top