1
votes

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.

1
What are you exactly meaning with "something that involves DB"? I guess it would be easier to recommend some proper way to achieve that goal if we know more about your situation. Until better knowledge, I personally would go by calling like $this->{$this->modelClass}->method() - makallio85
@makallio85 it doesn't matter what. All I'm asking is whether it's acceptable to use the AppModel in the AppController, in the way described above. I understand there are different approaches.. but is the one described above ok to use? - Andy
I would say, that I cant imagine any reason to implement such logic. But I think this is primarly opinion based question, so I will flag this one. - makallio85

1 Answers

2
votes

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.