Models in CodeIgniter
×

Models in CodeIgniter

1993

  • In Codeigniter, a model is used to handles the data stored in the database.
  • It is a class designed to work with information stored in the database.
  • Model files are created into the application/models directory.

Related Topic

Views in Codeigniter
Codeigniter Interview Questions

Syntax:

<?php
Class Model_name extends CI_Model{

Public function __construct(){
parent::__construct();
}
}
?>

Explanation:

  • Model_name: It represents the name of the model which we want to create. The first letter of the model name must be in uppercase. The name of the model class and file must be the same.
  • CI_Model: It is a predefined Codeigniter class. every model extends this class to inherit the predefined public methods and variables of CI_Model.

Creating a model:

Create a file First_model.php into the application/models directory and save the following code in it.

<?php
Class First_model extends CI_Model{
public function __construct(){
parent::__construct();
}

Public function display(){
echo "This is my first model";
}
}
?>

Calling a model:

We can load a model with the help of a controller.

Syntax:

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

Explanation:

  • this keyword is used for self-referencing.
  • load is the object of CI_Model class which we inherit in our First_model class.
  • model is a method of CI_Model class which we used to load the content of the given model.

To use the method of the loaded model, we have to use the following code.

$this->model_name->method_name();

Where model_name is the name of model and method_name represents a method of model_name model.

Note:

If you would like your model assigned to a different object name you can specify it via the second parameter of the loading function:

$this->load->model("Model_name","short");
$this->short->function_name();

Related Topics:

Codeigniter MVC Framework
Codeigniter controllers

Example:

Now, we add this line into our controller file application/controllers/Demo.php to load our model First_model.

Demo.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Demo extends CI_Controller{
public function index()
{
$this->load->model("First_model");
$this->First_model->display();
}

}
?>

Output:



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments