8

How do I access a controller method from inside a model?

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
+1 indeed. The MVC life works best if it's followed.
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.
5

You can use like this:

class some_model extends Model
{
   function getController()
   {
   $controllerInstance = & get_instance();
   $controllerData = $controllerInstance->getData();
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.