How do I access a controller method from inside a model?
2 Answers
You don't.
Although it is technically possible, if you think that you need to, it suggests a flaw in your application's design.
The Controller layer is the backbone of you application and meant to handle requests from the user, talk to the Model layer, and stitch together the output in the View. Your Model layer should be blind to the Controller and View, but deal with data manipulation only. This is an over-simplified explanation of the MVC pattern (you can find resources for that elsewhere).
Your Codeigniter models should be reusable from any controller, and not dependent on them. There are many solutions to solve whatever problem it is that you have: You can pass data into a model in a number of ways, or you can use the result of a call to a model's method to perform an action in your Controller.

- 1
- 1

- 101,186
- 37
- 194
- 228
-
Well you can just use `get_instance()->some_method()`. The real "hack" is that it only works in the context of a controller that actually has `some_method()` defined, and even still it might do something completely different in different controllers. If not used very carefully, there can be all kinds of crazy behavior. I can't discourage it enough. – Wesley Murch Mar 05 '12 at 08:32
-
+1 indeed. The MVC life works best if it's followed. – enchance Sep 26 '14 at 13:03
-
What about the case of callbacks? We design a generic, generally useful, model method that has some missing pieces to be supplied by the calling controller. The controller calls the model method and provides a callback function names in a parameters to provide these missing parts. Is that "bad design"? If so, lots of CI seems to do this bad thing. – Chris Nadovich Nov 15 '18 at 15:33
You can use like this:
class some_model extends Model
{
function getController()
{
$controllerInstance = & get_instance();
$controllerData = $controllerInstance->getData();
}
}

- 1,507
- 3
- 21
- 43