Reputation: 513
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";
}
}
Upvotes: 0
Views: 469
Reputation: 1171
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.
Upvotes: 2