Welcome Guest, Not a member yet? Register   Sign In
What is the best way to use a model from a helper?
#1

[eluser]Unknown[/eluser]
First question from a CI->noob(). I am refactoring some code that uses a lot of helper functions. The original developer has placed SQL in here, which is rather disturbing.

Anyway, I wrote a model, and then from a controller, I loaded my model and stuck it in a global like so:
Code:
$this->load->model('Model_Name');
$GLOBALS['model_name'] = $this->Model_Name;

The helper can then call the model's methods like so:
Code:
$GLOBALS['model_name']->model_method($id);
This is better, but far from ideal.

So is there a better way of achieving same?
#2

[eluser]CroNiX[/eluser]
Code:
function my_helper()
{
  //get CI instance
  $CI =& get_instance();
  //load the model
  $CI->load->model('my_model');
  //use the model
  $some_data = $CI->my_model->do_something();
}
#3

[eluser]bubbafoley[/eluser]
edit: beat me to it Wink
#4

[eluser]Unknown[/eluser]
Okay cool, makes sense. Thanks! If I've already loaded the model in the controller that is rendering a view that is calling functions in the helper, do I need to re-load the model in each helper function?

I'm guessing that to do so won't hurt anything because CI won't load a model it already has loaded. Correct?




Theme © iAndrew 2016 - Forum software by © MyBB