Welcome Guest, Not a member yet? Register   Sign In
Variable assignment - in controller or model? Advice please
#1

[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
#2

[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.
#3

[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
#4

[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
#5

[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




Theme © iAndrew 2016 - Forum software by © MyBB