CodeIgniter MVC(Model View Controller) Framework with Example

What is MVC?

MVC standards for Model-View-Control. It is an architectural pattern that splits the application into three major components.

1. Model deals with business logic and database interactions

2. Controller coordinates the activities between the model and the view

3. View is responsible for data presentation

The following are some of the advantages of MVC architectural pattern

In this tutorial, you will learn:

Model

The model is responsible for interacting with data sources. This is usually a database, but it can also be a service that provides the requested data. It is also a common practice to have the business logic contained in the models as opposed to the controller. This practice is usually termed fat model skinny controller.

The model usually writes data into the database, provides a mechanism for editing and updating, and deleting data. In a modern web application, models use data access design patterns such as active record to make interacting with the database easier.

For example, CodeIgniter uses a built-in library Active Record to aid the models while other frameworks such as Laravel use Eloquent Object Relational Mapper (ORM) that aids data access.

Controller

The controller listens for incoming requests for resources from the users. It acts as the intermediate between the model and the view and at times implements some business rules as well. Let's say the controller receives a request to register a user in the database.

The controller may perform data validation on what has been submitted to ensure that all the required parameters have been submitted. If something is missing the user is redirected to the registration page with the appropriate error message displayed. The controller may also request the model to perform more validation by checking if the submitted email address already exists. If all validation rules pass then the controller submits the data to the model for process and waits for the response.

Once the model has processed the information and returned a positive response, the controller loads the appropriate view and passes in the data returned from the model as a parameter.

View

The view deals with data presented to the end user. In web applications, views often contain HTML, CSS, and optionally JavaScript. Views contain minimum programming code. The code contained in views is usually used to loop through collections of data received as parameters from the model or helper function for cleaning up data or creating links to edit the records. Most modern web application usually uses templating engines that define their own syntax which is more like pseudocode and can easily be understood by designers. When working with CodeIgniter, it is common practice to use short PHP tags and control structures. To display something in CodeIgniter, one might use the following code

<?=$title?>

As opposed to

<?php
echo $title;
?>

Control structures are usually written as follows

<?php foreach ($customers as $customer): ?>
<li>
<p><?=$customer->first_name?><p>
</li>
<?php endforeach; ?>

As you can see from the above example, the view will use a combination of PHP and HTML instead of enclosing everything in pure PHP code.

How MVC frameworks work?

The following image shows the MVC framework works

A controller receives the request from the user, interacts with the database model if necessary then returns the result back to the browser in the form of HTML code which the browser interpreted into a human-readable format and displayed to the user.

CodeIgniter Controller

Let's now breakdown what just happened when we loaded the above URL into the web browser.

Open the file Welcome.php controller located application/controllers

You should be able to see the following code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {
	public function index()
	{
		$this->load->view('welcome_message');
	}
}

HERE,

We will now update the index method as follows

public function index()
    {
            $this->load->model('customers_model');

            $data['customer'] = $this->customers_model->get_customer(3);

            $this->load->view('welcome_message',$data);
    }

HERE,

CodeIgniter Model

Let's now create the view that we referenced in the above code. For simplicity's, our model will not interact with the database but will return a static customer record. We will work with databases in the next tutorials.

Create a file Customers_model.php in application/models

Add the following code

<?php
class Customers_model extends CI_Model {
    public function get_customer($id) {
        $data['id'] = 3;
        $data['first_name'] = 'John';
        $data['last_name'] = 'Doe';
        $data['address'] = 'Kingstone';

        return $data;
    }
}

HERE,

That is, it for our model. Let's now modify the welcome_message view

Open welcome_message.php located in

application/views/welcome_message.php

Replace the code with the following

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>CodeIgniter MVC Basics</title>
</head>
<body>
	<h1>Customer Details Card</h1>

	<p>Customer ID : <strong><?=$customer['id']?></strong></p>
	<p>First Name  : <strong><?=$customer['first_name']?></strong></p>
	<p>Last Name   : <strong><?=$customer['last_name']?></strong></p>
	<p>Address     : <strong><?=$customer['address']?></strong></p>
</body>
</html>

Save the changes

Load the following URL in the web browser

http://localhost:3000/

You should be able to see the customer card as shown in the image below

Summary

 

YOU MIGHT LIKE: