Skip to content
World Wide Web Server edited this page Jul 4, 2012 · 3 revisions

Hi all, this is what i am using as my model library to simplify the work in my models, i don't go much into complicated stuff, cause i like to keep the stuff simply, following the CI's simple pattern. My idea is to put the logic of getting query results into separate library that will extend the native model and use those methods into my models. So this is how i am doing it: In the application/libraries folder, create new file called MY_Model.php and in it: [code] <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

//It extends the native model and all other models in the application/model will extend this one class MY_Model extends Model { //The constructor function MY_Model() { parent::Model(); }

    //This function gets sql statement as argument
    //Returns set of objects
function obj_more($sql)
{
           //We initialize empty array.
    $rows = array();

           //Execute the query
    $q = $this->db->query($sql);

           //If we have results, loop through them and fetch each as object.
    if($q->num_rows() > 0)
    {
        foreach($q->result() as $row)
        {
            $rows[] = $row;
        }
        $q->free_result();

                    //Return the fetched objects in an array.
        return $rows;
    }
            //If there are no results, return FALSE.
    return FALSE;
}


    //Same as the above, but it returns only one object.
function obj_one($sql)
{
    $q = $this->db->query($sql);
           //We need exactly one row
    if($q->num_rows() == 1)
    {
        $row = $q->row();
        $q->free_result();
        return $row;
    }
            //if num_rows is different than 1
    return FALSE;
}


    //If someone wants the results returned as arrays, use this function
function arr_more($sql)
{
    $rows = array();
    $q = $this->db->query($sql);
    if($q->num_rows() > 0)
    {
        foreach($q->result_array() as $row)
        {
            $rows[] = $row;
        }
        $q->free_result();
        return $rows;
    }
    return FALSE;
}

    //This one returns only one row as array.
function arr_one($sql)
{
    $q = $this->db->query($sql);
    if($q->num_rows() == 1)
    {
        $row = $q->row_array();
        $q->free_result();
        return $row;
    }
    return FALSE;
}

    //These are helpers methods if you want to fetch all the rows from a given table:

    //Returns results as objects
function get_all_objects($table, $field = 'id', $ord = 'ASC')
{
    $sql = "SELECT * FROM ".$table." ORDER BY ".$field." ".$ord;
    return $this->obj_more($sql);
}


    //Returns results as arrays.
function get_all_arrays($table = '', $field = 'id', $ord = 'ASC')
{
    $sql = "SELECT * FROM ".$table." ORDER BY ".$field." ".$ord;
    return $this->arr_more($sql);
}

} [/code]

Using this library is very simple, in your models you can do this: [code] <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MProducts extends MY_Model { //Constructor function MProducts() { parent::MY_Model(); }

//We add 2nd argument which default is object, but if you want the product returned as array: use: get_product($id, 'arr');
function get_product($id, $r = 'obj')
{
  //Make sure the id is integer.
  $id = (int) $id;
  $sql = "SELECT * FROM products WHERE id=$id LIMIT 1";
  switch($r)
  {
     case 'obj':
     return $this->obj_one($sql);
     break;

     case 'arr':
     return $this->arr_one($sql);
     break;
  }
}

//Similar to the above function, but returns set instead one row.
function get_products_by_cat($cat_id, $r = 'obj')
{
   $cat_id = (int) $cat_id;
   $sql = "SELECT * FROM products WHERE category_id=$cat_id";
   switch($r)
   {
     case 'obj':
     return $this->obj_more($sql);
     break;

     case 'arr':
     return $this->arr_more($sql);
     break;
   }
}

//Returns all products as objects
function get_all()
{
   return $this->get_all_objects('products');
 }

} [/code]

This way we can have models that will be full of sql statements only and returning one of the parent's function with the sql passed in. Another good thing is that the methods return either object(s), either array(s) of rows or they return FALSE on failure.

Then in your controller you can use the model like this: [code] <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Products extends Controller { function Products() { parent::Controller(); }

function view($id) { //First make sure you get the id: if(!$id) { redirect('home'); } $this->load->model('MProducts');

 //This will return object, cause we didn't specify the 2nd argument.
 $product = $this->MProducts->get_product($id);
 if(!$product)
 {
    //cause the id is passed through the url, users can pass anything
    //so we must check if the product really exists
    redirect('home');
 }

 //Product is valid.
 $data['product'] = $product;

 //We can check here same, but you already know how to do that.
//This will return all products as objects
 $data['all_products'] = $this->MProducts->get_all();
 $this->load->view('product_view', $data);

}

} [/code]

In your view you can easily use the passed data. [code]

Product number: <?php echo $product->id; ?>


All products:

<?php foreach($all_products as $p): ?> echo $p->id; echo $p->price; .... <?php endforeach; ?> [/code] It's simple and it saves you typing code in your model, at least it's pretty helpful to me, so i decided to share it with the great community.
Clone this wiki locally