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

  • Loose coupling -the components exist and function independently of each other.
  • Flexibility – one can easily make changes to individual components
  • Increased productivity – more than one person can work on the project at the same time. The front-end developers can work on views and presentation while backend developers can focus on models and since the system is loosely coupled, it works at the end of the day

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,

  • defined('BASEPATH') OR exit('No direct script access allowed'); prevents direct access to the controller if the request didn't come through index.php. this is for security purposes.
  • class Welcome extends CI_Controller {…} defines the Welcome controller class and extends the parent class CI_Controller
  • public function index(){…} defines the index method that responds to the URL http://localhost:3000
    • $this->load->view('welcome_message'); loads the view welcome_message that is located in application/views directory

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,

  • $this->load->model('customers_model'); loads the customers model.
  • $data['customer'] = $this->customers_model->get_customer(3); calls the get_customer method of customers_model and passes in the parameter 3. In this example we have hard coded the value but in real life applications this would be a parameter from the URI.
  • $this->load->view('welcome_message',$data); loads the welcome_message view and passes in the $data variable to the view

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,

  • class Customers_model extends CI_Model {…} defines the model Customers_model that extends CI_Model.
  • public function get_customer($id) {…} defines the get customer method based on a customer id
  • $data[…] defines the static values of our fictious customer. This should be a row returned from the database.
  • return $data; returns the customer data.

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

  • MVC is an architectural pattern that splits the application into three major components
  • The model is responsible for interacting with data sources
  • The controller listens for incoming requests for resources from the users
  • In web applications, views often contain HTML, CSS, and optionally JavaScript
  • 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

 

YOU MIGHT LIKE: