Untangling MVC with CodeIgniter

When I first started programming the only type of code I wrote was procedural. You know the type, one thing leads to another with a thrown in function here and there and you have a working application. As I grew as a programmer, I began to find out that way of programming is fine for small projects but when I started to develop bigger applications my code became very disorganized and hard to read. To combat this I started writing my own classes to help me write better, reusable code that I could use in all my applications. Then I realized that although I was learning a lot by doing this, I was reinventing the wheel. Most of what I was writing had already been accomplished many times over in various PHP frameworks. I began looking into the almost endless selection of PHP frameworks and saw most of them were also based on something called MVC.

Learning to program using MVC was a complete paradigm shift for me, but it was well worth the struggle. If you want to develop applications with sell-structured, readable code that you can quickly diagnose problems in, then MVC is for you. In this article I’ll untangle the mysteries of MVC for you using CodeIgniter, a PHP framework based on the MVC pattern. I’ll first present a high level overview of MVC, what it is and how it can help you to become a better programmer, and then guide you through writing a simple web form the CodeIgniter way so you can see how the pattern looks in action.

What is MVC?

MVC is another acronym you’ll want to add to your endless book of acronyms; it stands for Model-View-Controller and is an software architectural design pattern. Adhering to the MVC pattern of will separate your application’s logic from its data and presentation. If you have ever seen code like this:

<?php if($somthing == $thisthing) echo "<p>Hello there</p>"; ?>

then you completely understand how a page full of mixed up PHP and HTML can become really hard to maintain and read. So let’s look at each part of MVC and see what each part represents.

  • Model – encapsulates your data management routines. Usually this is the part of your code that retrieves, inserts, updates, and deletes data in you database (or whatever else you’re using for a data store).
  • View – encapsulates the information that is presented to a user. This is the actual web page, RSS feed, or even a part of a page like a header of footer.
  • Controller – coordinates the Model and View parts of your application to respond to the request. A controller accepts input from the user and instructs the model and a view to perform actions based on that input; it controls the flow of information in the application.

To better understand how the MVC pattern works, let’s look at the steps you would take to code a PHP form using this pattern.

  1. The user interacts with the View which presents a web form.
  2. The user submits the form, and the Controller receives the POST request. It passes this data to the Model.
  3. The Model updates and queries the database and sends the result back to the Controller.
  4. The Controller passes the Model’s response to the View.
  5. The View updates itself with the new data and is displayed to the user.

Installing CodeIgniter

With so many MVC frameworks out there, how do you decide which one to choose – don’t they all provide similar functionality just differing slightly in their implementation and syntax? I had never used a framework before so I had to read through a lot of documentation and experiment with them to find out which one was right for me. I found that CodeIgniter had a much smaller learning curve then the others, which is probably why it has a reputation for being great for beginners. It’s documentation is very clear and provides many code examples to help you along the way. Although in this article I’ll be using CodeIgniter, the concept of MVC will be applicable to almost any framework you choose.

CodeIgniter is a cinch to install and configure for you system. Follow these steps and you’ll be up and running in less then five minutes.

  1. Download the latest version of CodeIgniter. As of this writing, the latest version is 2.0.3.
  2. Uncompress the archive and place the uncompressed directory in your web root.
  3. Rename the directory from CodeIgniter_2.0.3 to CI
  4. Open CI/application/config/config.php and change the base URL to your server. In my case, it is: $config['base_url'] = "http://localhost/CI";
  5. Go to the CI directory on the server using your web browser. Again, in my case it’s http://localhost/CI.

You’ve now finished the CodeIgniter installation and should see a web page like the one below:

mvc-ci-01

Now that you have everything installed you’ll have probably noticed all the directories that CodeIgniter has. Don’t be intimidated; you won’t have to deal with most of them since the majority of your work will take place in the system/application directory.

Looking in the system/application directory there are subdirectories named controllers, models, and views. This is where you will place your files for your application. Your controller files will be in the controllers directory, model files in the models directory, and view files in the views directory.

Less Talk, More Code

Now that you have a basic understanding of what the MVC architecture is and have CodeIgniter installed, let’s get down to some coding. In this example you’ll create a very simple form to collect email addresses using CodeIgniter’s form helper classes and form validation library. Let’s get started.

Create the Controller

Create a new file in your application/controllers directory named sitepointform.php that contains the following code:

<?php
class Sitepointform extends CI_Controller
{
    public function index() {
        // Load the Form helper which provides methods to assist
        // working with forms.
        $this->load->helper("form");
        // Load the form validation classes
        $this->load->library("form_validation");

        // As you have loaded the validation classes, you can now
        // apply rules to the fields you want validated. The
        // functions below take three arguments:
        //     1. The name of form field
        //     2. The human name of the field to be displayed in
        //        the event of an error
        //     3. The names of the validation rules to apply
        $this->form_validation->set_rules("first", "First Name",
            "required");
        $this->form_validation->set_rules("last", "Last Name",
            "required");
        $this->form_validation->set_rules("email", "Email Address",
            "required|valid_email");

        // Check whether the form validates. If not, present the
        // form view otherwise present the success view.
        if ($this->form_validation->run() == false) {
            $this->load->view("sitepointform_view");
        }
        else {
            $this->load->view("formsuccess");
        }
    }
}

Create the Views

Next, create a file in your application/views directory called sitepointform_view.php with this code:

<?php
// Display any form validation error messages
echo validation_errors();

// Using the form helper to help create the start of the form code
echo form_open("sitepointform");
?>
   <label for="first">First Name</label>
   <input type="text" name="first"><br>

   <label for="last">Last Name</label>
   <input type="text" name="last"><br>

   <label for="email">Email Address</label>
   <input type="text" name="email"><br>

   <input type="submit" name="submit" value="Submit">
 </form>
</html>

Create the file application/views/formsuccess_view.php with this code which will be showed later when a form is successfully submitted:

<html>
 <head>
  <title>Form Success</title>
  </head>
 <body>
  <h3>Your form was successfully submitted!</h3>
  <p><a href="http://localhost/CI/index.php/sitepointform">Enter a new
email address!</a></p>
 </body>
</html>

Now visit http://localhost/CI/index.php/sitepointform/index and you’ll see your newly created form:

mvc-ci-02

The URL follows this pattern in your application:

http://yourwebroot/[controller-class]/[controller-method]/[agruments]

Here sitepointform is the controller class, and index is the desired method. If you were renamed the method to myForm(), the URL would change like this:

http://localhost/CI/index.php/sitepointform/myForm

In the absence of a method in the URL, CodeIgniter will assume index.

Hit submit without any input in the text fields to try out the validation. You’ll see CodeIgniter enforcing the rules you set up earlier in the controller and displays the error messages.

Create the Model

Now that you have your form built, you need somewhere to store all the names and email addresses. Create a table addresses with the following statement in your database:

CREATE TABLE addresses (
    id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
    last_name VARCHAR(128) NOT NULL,
    first_name VARCHAR(128) NOT NULL,
    email VARCHAR(128) NOT NULL,
    PRIMARY KEY (id)
);

With the database table in place, now you have to tell CodeIgniter where it is. Open up application/config/database.php and enter your database credentials. Specify appropriate values for the hostname, username, password, database, and dbdriver keys.

Then, create application/models/sitepointform_model.php with this code:

<?php
class Sitepointform_model extends CI_Model
{
    public function insert_address($data) {
        $this->load->database();
        $this->db->insert("addresses", $data);
    }
}

The class has a method named insert_address() that is accepts the array of values passed in from the controller. CodeIgniter has a database class built in so you don’t have to write any SQL at all; $this->db->insert() will automatically generate and execute the SQL for you.

Try it Out

To use the model from the controller, open up application/controllers/sitepointform.php and update the index() method as follows:

<?php
public function index() {
    $this->load->helper("form");
    $this->load->library("form_validation");

    $this->form_validation->set_rules("first", "First Name",
        "required");
    $this->form_validation->set_rules("last", "Last Name",
        "required");
    $this->form_validation->set_rules("email", "Email Address",
        "required|valid_email");

    if ($this->form_validation->run() == false) {
        $this->load->view("sitepointform_view");
    }
    else {
        $first = $_POST["first"];
        $last = $_POST["last"];
        $email = $_POST["email"];
        $data = array("first_name" => $first,
                      "last_name" => $last,
                      "email" => $email);

        $this->load->model("sitepointform_model");
        $this->sitepointform_model->insert_address($data);
        $this->load->view("formsuccess");
    }
}

The incoming data posted from the form is placed into an associative array to be passed into the model’s insert_address() method. Note the keys in the array have the same names as the columns in the addresses table. This is important for the final step in creating the model. Then the model is loaded with $this->load->model(), the data is passed to the insert_address() method, and the success view is displayed.

Go back to http://localhost/CI/index.php/sitepointform and enter some data. If you fill in all the text fields correctly you’ll see the success page and the data is now in your database.

mvc-ci-03

Summary

Hopefully you now understand what MVC is all about, a way of separating pieces of your code based on their function to keep everything more organized. Though CodeIgniter happens to be my framework of choice, knowledge of the pattern is applicable to almost any other framework you choose, and of course you can implement it in your own code without a framework as well.

Image via Alexey Rozhanovsky / Shutterstock

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Selorm Nelson

    Thanks a lot for this, I’m working on a new project and torn between creating my own Tiny MVC or using an existing one and if the MVC code structure is really necessary. :)

    • Stephen Thorpe

      Thanks Selorm this was my first tech article so I’m glad it could help you with you new project. Don’t forget to “Like” or “tweet” the article around, you never know it could help others in the same boat as you. Thanks for visiting phpmaster.com

  • Z

    Thanks a lot! Hopefully there are more CI tutorials to come and hopefully also it cover on building application like shopping cart, cms or so on.

    Good job!

    • Stephen Thorpe

      Z if those are the type of articles that people are asking for I know we will have more in the near future. Keep us posted on any other ideas you would like to see. Thanks.

  • http://WebsiteURL Navid

    Thanks for this great tutorial. I always wanted to know how to implement this architecture in PHP and here i found CodeIgniter.

  • http://www.affordablewebsitepublishing.com Alex

    Thanks for the article. I have just taken the plunge into MVC and am loving articles like these. I looked at CI, but in the end opted to build my own mini-framework and include components from other glue type libraries such as Zend. I’m sure that CI is great, but it seems to be very tightly wrapped, I seem to learn best by figuring out and writing the code myself. One area of division I have found in different articles about MVC is how much should be in the controller (thick or thin) and if the view should be able to communicate with the model directly. Thanks again!

    • http://www.yoga-singapore.com Kian Ann

      Hey Alex – From what I read from other tutorials, business logic is best kept in Models, so thin controller, thick models would be good practise.

      Thanks for the article Stephen! I am also just diving into CodeIgniter, though I did Struts (a Java MVC) a loooooooong time ago!

      • http://www.thomasmultimedia.com.au Steve

        Whilst this tutorial is not perfect it does correctly show how to use a model; that is to keep it lean so that it does not need to concern itself with where the data is coming from.

        Likewise the model does not need to concern itself with whether the data meets certain application-specific criteria – that is the job of the controller. A lean model is a flexible model.

        If you always pass your form data to the model in an array, then down the track you can pass in data from another source (ie. an API) without having to redesign the model.

        • NotImportant

          Not according to pattern pundits/practitioners :o fat model – thin controller is definitely the accepted best practice – that includes validation and most logic.

    • http://www.edgeneering.com Myles

      The controller is your interface to the outside world. Its not designed to handle transforms or business logic. Its how your HTTP requests come in or SOAP, etc. So you use it like a gatekeeper, parse incoming data, validate it, and then dispatch it to a model to be transformed. The result of the transform then returns back to the controller where you handle the reverse side of the API (ie. sending it back out in a web page, SOAP response, etc.). Pretty simple really.

      Views just complicate the whole thing and are really less architectural. Think of them as Smarty tagged pages.

  • http://www.paulund.co.uk Paul

    Nice article I’ve recently got into MVC and it’s so better and cleaner to work with. The framework I use is also Codeigniter so easy to install and use, for both small and large projects.

  • http://www.designofseven.com designofseven

    Kohana > Code Igniter :) :)

  • Jono

    Never ever (ever!) use $_POST.
    Its always $this->input->post()

    • http://bluedream.tv N Oliver

      I take it $this->input is sanitized?
      (For those still using POST or GET outside of Intro Articles and Tutorials, search “SQL injection”. Assuming $this->input is sanitized, that’s a lot of heavy lifting done for you already! [Which is the point of a framework :] )

  • http://www.edgeneering.com Myles

    There’s a wealth of further info in the Forums at Codeigniter dot com. Well worth a visit. There’s a Wiki there too.

  • Tac

    Thanks for the article. We switched to CodeIgniter about a year ago, and it’s been great. I highly recommend using Smarty or Twig for your views. Makes a world of difference.

    Although I quite like CI, we’re now switching to Symfony2 for even more sophisticated applications, but there’s a steep learning curve. But now that we’ve bought into MVC it makes the evolution pretty natural.

  • Dorsey

    In my experience, CodeIngiter is probably not the best choice as a learning tool because it’s complication and has a huge execution overhead. Selecting a bare-bones MVC framework like SevinKevins would have been much better.

  • Destrehan Dave

    Thanks for the demo… anybody up to ‘translating’ this to VB.net or C# Using VS 2008 or 10?

    DD

  • Anne-Mie

    Anyone worked with Kohana? a fork of Codeignitor.

  • http://www.englishpubpool.co.uk NipponMonkey

    Nice article, just a note though: CI moved the application folder out of the system folder when version 2 was released. So you’ll find the application folder next to the system folder, not in it, “system/application”, like stated in the article.

  • Squirell

    Thanks for the tutorial. I’m also torn between ‘modifying the wheel’ i.e. creating my own small MVC framework or learning one of those out there (currently considering Yii Framework). Could you do an article on the pros and cons of building one’s own MVC Framework? Thanks

  • http://dewsworld.info Dewsworld

    thanks for the post…!

  • Dakota

    This is the best advice in the codeigniter game right now.

  • http://d3nnnis.com Denis

    Thank you for this great article. I’m just learning right now MVC so this really help me to understand how MVC works and i’m sure this will help me on my first project.
    Denis

  • Ajay

    Thanks for help

  • Mike

    I was searching for easy tutorial of CI and found here, thanks a lot to be a starter.

  • http://www.phpcourse.in jigar

    Hello Stephen , a great article from you. can you post one more article regarding simple blog project in CI? waiting for your post….

    Thank you again

  • Pankaj

    Very nice tutorial or beginners !!!!

    Excellent…

    Thanks
    Pannkaj

  • http://learnwebtips.blogspot.com/ Ashkar

    Thank you very much Stephen.. !!! Nice tutorial….

  • http://none Speedovic

    Excellent job… I was wondering if anyone has made changes to this code in order to retrieve data. For example type the name of the person and get the record details.. My plan is to expand this to location so I can search on location and I get all people living in LONDON. I have made changes to the table that’t an issue … I have problems writing the search code. Thx for any help or suggestions.

  • http://none Speedovic

    I need some help to put this code in MVC any help would be appreciated. It is a simple form which retrieve data from an SQL DB.. it works fine as one PHP file but I have problems to put it in MVC.

    Search Contacts Details
    You may search either by first or last name

    /body>

    <?php
    if(isset($_POST['submit'])){
    if(isset($_GET['go'])){
    if(preg_match("/[A-Z | a-z]+/", $_POST['name']))
    {

    $name=$_POST['name'];

    //-query the database table
    $sql="SELECT * FROM Contacts WHERE FirstName LIKE '%" . $name . "%' OR LastName LIKE '%" . $name ."%'";

    //-run the query against the mysql query function
    $result=mysql_query($sql);

    //-create while loop and loop through result set
    while($row=mysql_fetch_array($result)){

    $FirstName =$row['FirstName'];
    $LastName=$row['LastName'];
    $ID=$row['ID'];
    $Email=$row['Email'];

    //-display the result of the array

    //echo "n”;
    echo “” . “” .$FirstName . ” ” . $LastName . “n”;
    echo “$FirstName” . “&nbsp” . “$LastName” . “&nbsp” .”ID” . “&nbsp” .”$Email”;
    //echo “”;
    }
    }
    else{
    echo “Please enter a search query”;
    }
    }}
    //}
    ?>

  • Speedovic

    Search Contacts Details
    You may search either by first or last name

  • Vipul Patil

    simply superb work , I was facing issue with codeigniter as I am nebie to CI,i had tried tutorial from CI official site but it never worked infact no one answered my queries on forum. I was like frustrated,But you made me, Thanks alot!,In future Hoping for some more tutorials on CI…

    • Vipul Patil

      Sorry but just want add something, The controller file phpmasterform.php is having some error. yeah,last line is
      $this->load->view(“formsuccess”);
      but it should be
      $this->load->view(“formsuccess_view”);

  • https://www.facebook.com/?q=#/sohail.hussainali?ref=tn_tnmn Sohail

    I am getting the following error:
    A Database Error Occurred

    Error Number: 1146

    Table ‘login.addresses’ doesn’t exist

    INSERT INTO `addresses` (`first_name`, `last_name`, `email`) VALUES (‘Sohail’, ‘Barat’, ‘sohail_hussain_ali@hotmail.co.uk’)

    Filename: E:wampwwwCIsystemdatabaseDB_driver.php

    Line Number: 330

    can anyone tell me how to remove it ????