PHP MVC Framework Tutorial: CodeIgniter Example

What is PHP MVC framework?

PHP MVC is an application design pattern that separates the application data and business logic (model) from the presentation (view). MVC stands for Model, View & Controller.

The controller mediates between the models and views.

Think of the MVC design pattern as a car and the driver.

The car has the windscreens (view) which the driver (controller) uses to monitor traffic ahead then speed or brake (model) depending on what he sees ahead.

Why use PHP MVC Framework?

In this tutorial, you will learn-

PHP MVC Design Pattern

Let’s now briefly discuss each component of the MVC design pattern.

Model – this part is concerned with the business logic and the application data. It can be used to perform data validations, process data and store it. The data can come from;

Controller – this is the part deals with the users’ requests for resources from the server.

As an example, when the users requests for the URL …/index.php?products=list, the controller will load the products model to retrieve the products data then output the results in the list view.

In a nutshell, the controller links the models and views together depending on the requested resources.

Views – this part deals with presenting the data to the user. This is usually in form of HTML pages.

Types of PHP MVC framework

Selecting the best PHP framework is a challenge.

You don’t have to write your own framework to benefit from the advantages of MVC.

You should only attempt to create your own MVC related application design for understanding how MVC frameworks work.

Once you are comfortable with the way MVC frameworks work, you should move on to the mature and already tested frameworks.

The table below briefly describes some of the popular php frameworks and the features that each framework offers.

Framework Description
Learn PHP MVC Frameworks with CodeIgniter Example 
CodeIgniter
https://codeigniter.com/
It is one of the most popular PHP MVC frameworks. It’s lightweight and has a short learning curve. It has a rich set of libraries that help build websites and applications rapidly. Users with limited knowledge of OOP programming can also use it. CodeIgniter powered applications include;
Learn PHP MVC Frameworks with CodeIgniter Example
Kohana
http://kohanaframework.org
It’s a Hierarchical Model View Controller HMVC secure and lightweight framework. It has a rich set of components for developing applications rapidly. Companies that use Kohana include;
 Learn PHP MVC Frameworks with CodeIgniter Example
CakePHP
www.cakephp.org
It is modeled after Ruby on rails. It’s known for concepts such as software design patterns, convention over configuration, ActiveRecord etc. CakePHP powered applications include;
Learn PHP MVC Frameworks with CodeIgniter Example
www.framework.zend.com
Zend
It is a powerful framework that is;
  • Secure, reliable, fast, and scalable
  • Supports Web 2.0 and creation of web services.
It features APIs from vendors like Amazon, Google, Flickr, Yahoo etc. It’s ideal for developing business applications. Zend powered applications include;
  • Pimcore CMS,
  • DotKernel.
Companies using the Zend framework include;
  • BBC
  • Cisco
  • Webex
  • Offers.com

 

Porting the opinion poll application to CodeIgniter

In this tutorial, we created a PHP poll application. Here, we will port that code to CodeIgniter

Learn PHP MVC Frameworks with CodeIgniter Example

We are now going to port our opinion poll application to CodeIgniter. Recall that our application was divided into three major components namely the;

Database configuration settings

Learn PHP MVC Frameworks with CodeIgniter Example

Creating Our Model

Next we are going to create our model that will extend the CI_Model. The CI_Model is part of the CodeIgniter libraries. The model will be located in application/models opinion_poll_model.php

<?php 
class Opinion_poll_model extends CI_Model 
{ 
    public function __construct() 
    { 
    	$this->load->database(); 
    } 

    public function total_votes() 
    { 
    	$query = $this->db->select('COUNT(choice) as choices_count')->get('js_libraries');
        return $query->row()->choices_count; 
    } 

    public function get_results() 
    { 
    	$libraries = array("", "JQuery", "MooTools", "YUI Library", "Glow"); 
        $table_rows = ''; 

        for ($i = 1; $i < 5; $i++) 
        {
             $sql_stmt = "SELECT COUNT(choice) choices_count FROM js_libraries WHERE choice = $i;"; 
             $result = $model->

             select($sql_stmt); $table_rows .= "<tr><td>" . $ libraries [$i] . " Got:</td><td><b>" . $result[0] . "</b> votes</td></tr>"; 
        } 
        public function add_vote($choice) 
        { 
        	$ts = date("Y-m-d H:i:s"); $data = array('choice' => $choice, 'ts' => $ts); $this->db->insert('js_libraries', $data); 
        } 
   } 
?>

  HERE,

Creating Our Controller Let’s now create the controller. We will use the default CodeIgniter controller located in application/controllers/welcome.php. Replace its source codes with the following code.

<?php

if (!defined('BASEPATH'))  exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function __construct() {

        parent::__construct();

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

    }

    public function index() {

        if ($this->input->post('submitbutton') && !$this->input->post('vote')) {

            echo "<script>alert('You did not vote!');</script>";

        }

        if ($this->input->post('vote')) {

            $this->opinion_poll_model->add_vote($this->input->post('vote'));

            $data['total_votes'] = $this->opinion_poll_model->total_votes();

            $data['rows'] = $this->opinion_poll_model->get_results();

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

        } else {

            $this->load->view('opinion_poll_form');

        }

    }

}

/* End of file welcome.php */

/* Location: ./application/controllers/welcome.php */
?>

    HERE,

Creating Our Views

Recall from the previous example that we had two HTML pages, one for voting and the other for results. We will use the same HTML code with minimal modifications to create our views. Create the following files in application/views directory

opinion_poll_form.php 
<html>
<head>
    <title>
        JavaScript Libraries - Opinion Poll
    </title>
</head>

<body>
    <h2>JavaScript Libraries - Opinion Poll</h2>
    <p><b>What is your favorite JavaScript Library?</b></p>
    <form method="POST" action="index.php">
        <p>
            <input type="radio" name="vote" value="1" /> JQuery
            <br />
            <input type="radio" name="vote" value="2" /> MooTools
            <br />
            <input type="radio" name="vote" value="3" /> YUI Library
            <br />
            <input type="radio" name="vote" value="4" /> Glow </p>
        <p>
            <input type="submit" name="submitbutton" value="OK" />
        </p>
    </form>
</body>
</html>

  Let’s now create the results page results.php

<html>
    <head>
        <title>JavaScript Libraries - Opinion Poll Results</title>
    </head>
    <body>

        <h2>JavaScript Libraries - Opinion Poll Results</h2>

        <p><b>What is your favorite JavaScript Library?</b></p>

        <p><b><?php echo $total_votes; ?></b> people have thus far taken part in this poll:</p>

        <p><table><tr><td>

            <?php print($rows); ?>

        </tr></td></table></p>

        <p><a href="">Return to voting page</a></p>
</body>
</html>

 

Testing our application

Assuming the root directory of your application is ciopinion, browse to http://localhost/ciopionpoll/

Learn PHP MVC Frameworks with CodeIgniter Example

Click on OK button, you will see the following alert message

Learn PHP MVC Frameworks with CodeIgniter Example

Vote for your favorite candidate then click on OK You will see the following results page

Learn PHP MVC Frameworks with CodeIgniter Example

Conclusion

CodeIgniter is an easy to learn and use PHP MVC framework that can greatly reduce the time spent developing applications.

Summary

 

YOU MIGHT LIKE: