CodeIgniter Forums
Variable assignment - in controller or model? Advice please - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Variable assignment - in controller or model? Advice please (/showthread.php?tid=33866)



Variable assignment - in controller or model? Advice please - El Forum - 09-11-2010

[eluser]mikertjones[/eluser]
Hello all

I have written several applications with Codeigniter and I have been niggled by a question each time - but I have just got on with it without really trying to find an answer.

In a Controller I might declare a variable which is ultimately to hold the results returned from a database query.

class MyClass extends Controller {
var $myVar;

function MyClass()
{
parent::Controller();
$this->load->model('mymodel');
}
}

I can assign the value to $this->myVar in one of 2 ways:

As a return value from a model function call as

$this->myVar = $this->mymodel->modelfn();
and in the model..

function modelfn()
{
$qry=$this->db->get('mytable');
if($qry->num_rows()>0)
{
return $qry->result();
}
}

Or within the model function itself

so, in the controller...
$this->mymodel->modelfn();

and in the model...
function modelfn()
{
$qry=$this->db->get('mytable');
if($qry->num_rows()>0)
{
$this->myVar = $qry->result();
}
}

Is one way better than the other in some way? Is there best practice? Is there a need to be consistent?

Any thoughts would be welcome.

With many thanks and best wishes

Mike Jones


Variable assignment - in controller or model? Advice please - El Forum - 09-11-2010

[eluser]WanWizard[/eluser]
It depends on what you want to do with this variable.

The controller is the bridge between the models and the views, so if this variable contains data that is input for another model method or a view, store it in the controller. If it is local to the model, leave it in the model.


Variable assignment - in controller or model? Advice please - El Forum - 09-11-2010

[eluser]mikertjones[/eluser]
Thanks WanWizard

I understand your point about where the variable will be used but isn't the variable available in the project wherever the variable assignment is made?

Mike


Variable assignment - in controller or model? Advice please - El Forum - 09-11-2010

[eluser]Buso[/eluser]
Variables are available within their scope. Eg: If you save data to a private var in your model, you won't be able to see it from within your controller


Variable assignment - in controller or model? Advice please - El Forum - 09-11-2010

[eluser]InsiteFX[/eluser]
I do wish that the Mod's would put a sticky up on how
to use the forum code tags!
Code:
//CODE!

InsiteFX