Models are designed to exchange the data between database and controller or view. For an example, if you are managing books using CodeIgniter framework then definitely you have a model regarding books.

Model is a simple class with the help of which you can create the record of books, update their information, delete and read the record.

Model classes are created under application/models folder. Right below is example code for books model.

Books_model is the name of the model class which we are using in CodeIgniter. Each model must be inherited by CI_Model class to enhance its feature as a data access layer.

The things which are really critical to be noted is that the first letter of each model class must be capital.

There is another thing which you need to follow is that the name of the model file and the class need to be the same.

You must have to save the file having postfix of the model right after the underscore. Like we have a name of our books model file is “Books_model.php”.

Loading Model

Model can be utilized within another model and as conventional it’s used in the controller. In simple words, we used the model as a data access layer within a controller to exchange information between views and database.

User will post the data from view to controller and Controller will process that data then pass it to model by which it is stored in the database.

In this way, the user will not interact directly with the database. Below is the simple sentence of loading the modal within a controller.

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

In the above code “model_class_name” is the name of a model which you want to load within a controller for the exchange of data.

By the following code, you can access the model method.

$this->model_class_name->model_class_method_name();

For an example, we have a model class of books in which we will declare four methods to perform CRUD operations.

AutoLoad Model

Sometimes you have required to load some models throughout the application. In simple words when you want to use a model as a global scoped then you declared that in “autoload.php” file until the config folder of the application.

In the following code, you can observe how we have declared “Books_model” as a autoload throughout the application.

We just passed the name of our model in auto load array. Now you don’t need to load the model in any controller. You can just simply call the methods within that model. It is helpful when you have declared all the methods within one controller which you want to use throughout the application.

Tutorial Pace is Pakistan's first and only platform from where you can learn market demanding technologies right from developers. Tutorial Pace is developed by a developer for developers. We are working to maintain the quality of content and practical knowledge within our tutorials.