Reputation: 2797
I just want to know the performance for code structure and Codeigniter query builder work.
I have create My_model()
public function select_products_from($table, $limit = 0) {
$this->db->select('*');
$this->db->from($table);
if(!empty($limit)){ $this->db->limit($limit);}
$this->db->where(array('status' => 1));
$this->db->order_by('viewed', 'desc');
$dat a= $this->db->get();
$this->db->close();
return $data;
}
In my controller
private function dataProducts () {
$this->load->model('main/products/Products_model');
return $this->Products_model->select_products_from('products')->result();
}
public function sendView (){
$this->data['products'] = $this->dataProducts();
Render->$this->view('products',$this->data);
}
Usages, I want to use multiple method
return $this->Products_model->select_products_from('products')->last_row()
->first_row()
->last_row()
->next_row()
->previous_row()
->first_row()
->.....
Upvotes: 0
Views: 79
Reputation: 3608
Structurally, I strongly prefer returning the result of the query to the controller, rather than the query itself. That way all your database-related stuff is nicely compartmentalized in your model, along with error handling and dealing with special cases.
For instance, if your data schema changes, currently the effect of that change will ripple through your entire program. If you return a simple array of row data, you can make sure your model still returns something the controller can use.
Note that you can return each result row as an array or an object, and you can even have the rows be instances of a class you define. In this little snippet it returns null
when there are no results; you could return an empty array or whatever makes sense in your context:
$result = null;
<all the stuff to set up your query>
$query = this->db->get();
if ($query->num_rows() > 0) {
$result = $query->result();
}
return $result;
In you controller, you have an array of objects and you can use all php's array functions to play with it however you want. And no matter what you do to your database that part will be unaffected.
Upvotes: 1