Welcome Guest, Not a member yet? Register   Sign In
Return Query Object vs Returning Data?
#1

[eluser]JasonS[/eluser]
Hi,

Is there some definitive best practice for this? Lets take this simple example.

Controller:
Code:
<?php
class example extends Controller {
  public function index() {
    $this->load->model('example_model');
    $data['p'] = $this->example_model->get());
    $this->load->view('example', $data);
  }
}

From here you have 2 options.

I usually return the query object like this.

Model:
Code:
<?php
class example_model extends Model {
  public function get() {
    return $this->db->get('example_table');
  }
}

You would then have the view.
Code:
<?php if ($p->num_rows == 0): ?>
  <p class="error">There are no results to display</p>
&lt;?php else: ?&gt;
  &lt;?foreach($p->result() as $row): ?&gt;
    <p>&lt;?=$row->test?&gt;</p>
  &lt;?php endforeach;?&gt;
&lt;?php endif;?&gt;

That is one option. The main benefit of this is how little coding you need to do. Its like 3 lines in your model. The other option is create an array. So, instead of returning the query object you would loop through it and return an array.

The main benefit of this second option is that you can pre-process your data. The view is about the same. The difference being that you are interacting with an array instead of an object.

Which method do you use and why? OR do you use something else?




Theme © iAndrew 2016 - Forum software by © MyBB