Untangling MVC with CodeIgniter

blocks

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 phpmasterform.php that contains the following code:

<?php
class Phpmasterform 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("phpmasterform_view");
        }
        else {
            $this->load->view("formsuccess");
        }
    }
}

Create the Views

Next, create a file in your application/views directory called phpmasterform_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("phpmasterform");
?>
   <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/phpmasterform">Enter a new
email address!</a></p>
 </body>
</html>

Now visit http://localhost/CI/index.php/phpmasterform/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 phpmasterform 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/phpmasterform/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/phpmasterform_model.php with this code:

<?php
class Phpmasterform_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/phpmasterform.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("phpmasterform_view");
    }
    else {
        $first = $_POST["first"];
        $last = $_POST["last"];
        $email = $_POST["email"];
        $data = array("first_name" => $first,
                      "last_name" => $last,
                      "email" => $email);

        $this->load->model("phpmasterform_model");
        $this->phpmasterform_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/phpmasterform 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

Stephen Thorpe is originally from London but now living in Tennessee. He works at an Internet and Telephone company as an applications developer primarily using PHP and MySQL.

Visit Site

27 Responses to “Untangling MVC with CodeIgniter”

  1. Selorm Nelson December 7, 2011 at 10:12 am

    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 December 7, 2011 at 1:37 pm

      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

  2. Z December 7, 2011 at 10:21 am

    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 December 7, 2011 at 1:39 pm

      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.

  3. Navid December 7, 2011 at 1:46 pm

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

  4. Alex December 7, 2011 at 3:37 pm

    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!

    • Kian Ann December 7, 2011 at 9:06 pm

      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!

      • Steve December 13, 2011 at 9:54 pm

        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 December 19, 2011 at 7:45 am

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

    • Myles December 13, 2011 at 11:24 am

      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.

  5. Paul December 9, 2011 at 2:14 am

    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.

  6. designofseven December 9, 2011 at 7:07 am

    Kohana > Code Igniter :) :)

  7. Jono December 12, 2011 at 1:46 pm

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

    • N Oliver December 13, 2011 at 12:28 pm

      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 :] )

  8. Myles December 13, 2011 at 11:21 am

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

  9. Tac December 13, 2011 at 1:04 pm

    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.

  10. Dorsey December 13, 2011 at 1:14 pm

    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.

  11. Destrehan Dave December 13, 2011 at 2:25 pm

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

    DD

  12. Anne-Mie December 13, 2011 at 2:30 pm

    Anyone worked with Kohana? a fork of Codeignitor.

  13. NipponMonkey December 14, 2011 at 2:36 pm

    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.

  14. Squirell December 15, 2011 at 3:05 am

    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

  15. Dewsworld January 13, 2012 at 8:10 pm

    thanks for the post…!

  16. Dakota February 12, 2012 at 10:34 pm

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

  17. Denis February 21, 2012 at 5:04 pm

    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

  18. Ajay February 27, 2012 at 12:17 pm

    Thanks for help

  19. Mike March 28, 2012 at 7:27 am

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

Leave a comment

© 1998-2012 SitePoint Pty. Ltd. All Rights Reserved