CodeIgniter MVC (Model View Controller) Framework Example

โšก Smart Summary

CodeIgniter MVC Framework splits an application into Model, View, and Controller. The model handles data and business logic, the controller coordinates requests, and the view presents the result, giving loose coupling, flexibility, and higher developer productivity.

  • ๐Ÿ—๏ธ Core Pattern: MVC divides an application into model, view, and controller components.
  • ๐Ÿ’พ Model: Interacts with the data source and holds the business logic, often through Active Record.
  • ๐ŸŽ›๏ธ Controller: Listens for requests, validates input, and coordinates the model and view.
  • ๐Ÿ–ผ๏ธ View: Presents data as HTML, CSS, and minimal PHP, kept free of heavy logic.
  • ๐Ÿ”— Loose Coupling: Components work independently, so front-end and back-end work can run in parallel.
  • โšก Short Tags: CodeIgniter views commonly use short PHP echo tags for cleaner templates.
  • ๐Ÿ” Request Flow: Controller to model to view, then HTML back to the browser.

CodeIgniter MVC Framework

What is MVC?

MVC stands for Model-View-Controller. 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 the MVC architectural pattern:

  • Loose coupling โ€“ the components exist and function independently of each other.
  • Flexibility โ€“ you can easily make changes to individual components.
  • Increased productivity โ€“ more than one person can work on the project at the same time. Front-end developers can work on views and presentation, while back-end developers focus on models, and because the system is loosely coupled, it all works together in the end.

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 common practice to keep the business logic in the models rather than the controller. This practice is usually termed “fat model, skinny controller”.

The model usually writes data into the database and provides a mechanism for editing, 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 Active Record library to aid the models, while other frameworks such as Laravel use the Eloquent Object Relational Mapper (ORM) for data access.

Controller

The controller listens for incoming requests for resources from users. It acts as the intermediary between the model and the view, and at times implements some business rules as well. Suppose 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 all the required parameters are present. If something is missing, the user is redirected to the registration page with the appropriate error message. The controller may also ask the model to perform more validation, such as checking whether the submitted email address already exists. If all validation rules pass, the controller submits the data to the model for processing 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 minimal programming code, usually just enough to loop through collections of data received from the model, or a helper function for cleaning up data or creating edit links. Most modern web applications use templating engines with their own pseudocode-like syntax that designers can understand. When working with CodeIgniter, it is common practice to use short PHP tags and control structures. To display something in CodeIgniter, you 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 example above, the view uses a combination of PHP and HTML instead of enclosing everything in pure PHP code.

How MVC Frameworks Work

The following image shows how the MVC framework works.

How the MVC framework works

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

CodeIgniter Controller

Let us now break down what happened when we loaded the URL into the web browser. Open the file Welcome.php controller located in application/controllers. You should 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 did not 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 located in the 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 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.

CodeIgniter Model

Let us now create the model referenced in the code above. For simplicity, 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 and 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 fictitious customer. This should be a row returned from the database.
  • return $data; returns the customer data.

That is it for our model. Let us 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 and load the following URL in the web browser: http://localhost:3000/. You should see the customer card as shown in the image below.

Customer details card rendered by CodeIgniter

FAQs

It means the business logic lives in the model, keeping the controller thin and focused on routing requests. This makes the logic reusable and the controller easier to read and test.

A view should only present data. Keeping logic out of it separates concerns, so designers can edit the layout without touching business rules, and the same data can be shown in different views.

Active Record is a built-in query builder that lets models read and write the database with method calls instead of raw SQL. It also helps prevent SQL injection by escaping values.

AI can generate matching controller, model, and view files from a description of a feature, and keep naming consistent. Review the generated queries and validation before running them.

The short echo tag is a compact way to print a value in a view. The full php tag block is used for statements and control structures. Both are equivalent for output, but short tags keep views tidy.

Summarize this post with: