Search code examples
cakephpcakephp-2.x

CakePHP 2 - loading AppModel functionality in AppController


I've read the following post Calling AppModel function in AppController for cakephp where the OP has asked if they can use a function from their AppModel inside AppController.

The answer given doesn't really address the question (since it talks about using the AppModel in another model and not a controller).

So, is it acceptable to do something like this inside the AppController?

$this->loadModel('AppModel');
$this->AppModel->my_function();

The reasoning why someone may want to do this is because the AppController is run on every request. If you need to do something that involves your DB on every request, the logic for that may go in AppModel.php but be executed via AppController.php

Please note this applies to Cake 2.0 (not 3) as it is a legacy application we are dealing with.


Solution

  • As long as you are doing everything correctly you shouldn't need to load the AppModel in your controller as it should already be available through the model being used by the controller. Really you should never call AppModel directly as this is intended for sharing common logic between models which should extend the AppModel.

    So in your AppController you should already be able to access your function declared in your AppModel like this:-

    $this->{$this->modelClass}->my_function();
    

    In the above code {$this->modelClass} will determine the model class being used by the current controller so that you can easily use this within your AppController. So if you had a PagesController this would be interpreted as $this->Page->my_function().

    If this doesn't work for you then I'd suggest you've gone wrong in how you are developing with Cake and need to examine how you are using your models.