0

I am working on a Codeigniter project and I have seen accessing the controller from the model. I am wondering if $this->controller is the same or different as using $CI =& get_instance(). I am assuming no, but I am more familiar with the standard returning data from a function than this way. I have not seen Codeigniter examples doing this, so I don't think this is a suggested way of accessing the controller, but more of a hack:

class my_model extends CI_Model
{
    public function __construct()
    {
        $this->errors = array();
        parent::__construct();
        $this->controller = get_instance();
    }

    public function somefunc()
    {
        // Accessing controller 
        $this->controller->session->set_userdata('foo', 'bar');
        $this->controller->data = "fubar";
    }
}
2
  • 4
    I think this is anti-pattern. The controller should be the one to control the logic. You could do this by getting the return from the model function. Commented Sep 28, 2016 at 16:31
  • Yes agree with @phiter. But still you wants to access then try $this->controller =& get_instance(); Find detail answer here: stackoverflow.com/a/4740548/1578380 Commented Sep 28, 2016 at 16:58

1 Answer 1

2

This is not CI really, this is a modification. It might be simple_HMVC that is being used.

In normal CI usage, a model would return data.

somewhere in your app the $controller is being set as a controller object and as an alias in the CI super object. In this way hierarchical modular MVC is being implemented, so controller methods within modules can be called from other modules.

It seems that whether this is good practice or not is a matter of some debate. It is a bit of a hack but for simple_hmvc it is not a bad one IMHO necessarily but I would not do this. It seems to me that you are creating situations where debugging, unit testing or even just clarity of responsibility is being severely blurred and will cause trouble later down the line.

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

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.