How to use Codeigniter Models

First lets try to get some understanding of what a Modal is and What it does?

Models represents the data objects of an application. For an example in an E-Commerce site, what are the data objects that you can think of? If it is selling books, then a Book is a data object. Then there are Users. A User is also a data object, When some one places an Order which is also a data object. If it selling magazines, then a Magazine is also a data object. etc. As another example lets take a vehicle reservation web site. It may feature vehicles, drivers, vehicle categories, allow placing inquiries, allow vehicle reservations, allow guest comments etc. So again we can see number of data objects: a Vehicle, a Driver, a Category, an Inquiry, a Reservation, a Comment etc. So as mentioned earlier, Models are responsible for representing and manipulating (storing, retrieving, updating, deleting) data objects in an application as required by its functionality. That means if someone wants to view details of a particular book then there should be a Modal that represent Books and it should retrieve the information about the book we need. If we need to make an order there should be a Modal representing Orders and it should calculate and store order details in the database. If we need to publish a comment then we need its Modal to store and retrieve the comment. Models often interact with databases for its data persistence needs.

A Modal is basically a PHP class just like any other class you have seen. Lets see how to create a Model in Codeigniter:

Remember:

  • Model classes in Codeigniter must be saved at application/models directory
  • Every Modal class must extend the Codeigniter’s base model class CI_Model
  • Class name should start with a capital letter, and the rest must be in lower case. If you want to have two or more words, you can separate those with an underscore. Eg: Mymodal, My_modal
  • When saving, class’s file name must match its class name definition and must be in all lower case letters. For an example, if your Modal class defined as Mymodal then it must be saved as application/models/mymodal.php. If your Modal class name defined as My_modal then it must be saved as application/models/my_modal.php.

Below is a Modal class definition that you can use as a boilerplate for your Model definitions. Make sure you replace ‘Modal_name’ with your actual modal name:

	class Model_name extends CI_Model{

		public function __construct(){
			parent::__construct();
		}
	}

Below example shows a simple modal class for managing Orders of a fictional e-commerce application. It includes methods for storing an order, retrieving order information and listing orders:

	class Order_model extends CI_Model{

                public $customer_name;
                public $order_total;
                public $order_date;

		public function __construct(){
			parent::__construct();
		}

                public function save_order($orderData)
                {
                     // set customer name
                     $this->customer_name = $orderData['customer_name'];

                     // calculate order total
                     $this->order_total = $orderData['item_count'] * 5.99;

                     // set order date
                     $this->order_date = time();
                     
                     // add order details to the `orders` table
                     $this->db->insert('orders',$this);
                }

                public function get_order_list()
                {
                    $results = $this->db->get('orders');
                    return $results;
                }

                public function get_order_details($orderId)
                {
                    $result = $this->db->get_where('orders', array('id' => $orderId));
                    return $result;
                }
	}

Loading a Model

Before being able to use a model that you created, you have to load it from inside a Controller using the below statement syntax:

$this->load->model('model_name');

‘modal_name’ should match the file name of the modal class (without .php) stored in the application/models directory. Usually the Controller constructor is the best place to load a Modal. If not you can load it from any other controller method that the Model is needed.

Using a Model:

After a Model is loaded, you can use it from your controller methods using the below statement syntax:

$this->model_name->method();

Check out below example to see how to load and use the Order Model from a Controller. We have used ‘Order’ as the controller name but it doesn’t really matter. There is no relation between a controller name versus a model name being the same.

class Order extends CI_Controller {

        public function __construct()
        {
                parent::__construct();
                $this->load->model('order_model');
        }

        public function index()
        {
                // get a list of orders
                $data['orders'] = $this->order_model->get_order_list();

                // load order listing template
                $this->load->view('index', $data);
        }

        public function new_order()
        {
                // get submitted order data
                $orderdata = $this->input->post();

                // create a new order by passing $orderdata to the Order Model
                $this->order_model->save_order($orderdata);

                // show feedback
                $this->load->view('new_order_feedback')
        }
}

You can see we have loaded the Order Model in our controller constructor. Then in the index method we are calling get_order_list() method of the Order Model to retrieve a list of orders and we are passing that list to the order listing template that will show the orders. Secondly we have another controller method called ‘new_order()’ which takes the submitted order data and passes those data to the Order Model’s save_order() method. That will create a new order in the database. Finally it loads template that will show some feedback to the user.

This is the basic knowledge you need to work with Models in Codeigniter.

Comments

So empty here ... leave a comment!

Leave a Reply

Your email address will not be published. Required fields are marked *

Sidebar



Do NOT follow this link or you will be banned from the site!