9 min read

MVC:Model-View-Controller

What’s MVC all about? For sure at this time you are very curious about this. In short, MVC is an architectural pattern, a way of structuring our application.

system
          application
               models
               views
               controllers

As you can see there is a folder for each of the words (MVC); let’s see what we can put into them:

  • Models: The models represent our application data, be it in databases, in XML files or anywhere else. Also, interaction with databases is carried here. For example, models will allow us to fetch, modify, insert, and remove data from our database. All actions that require our application to talk to our database must be put in a model.
  • Views: Files placed here are responsible for showing our data to the visitors to our site, or users of our application. No programming logic, no insert or update queries must be run here, though data access may occur in these files. They are here only to show the results of the other two. So we fetch the data in the model, and show it in the view. Now, what if we need to process the data, for example, putting it into an array? Then we do it in the controller; let’s see how.
  • Controllers: These act as a nexus between models and views, and programming logic occurs here.

CodeIgniter 1.7

Take a look at this little diagram, in the left column we can see a “classical” way of doing things (a little outdated right now). We have a PHP file with SQL queries and HTML code in the same file and embedded into the HTML PHP logic.

It may seem, at first glance, that this way it is easier and faster to program. But in this case the code gets messed faster and becomes cluttered with SQL queries, HTML, and PHP logic. Look at the right-side column—we have SQL queries in the Model, HTML and other graphic elements in the View, and PHP logic in the Controller. Doesn’t that seem organized? The Controller calls and fetches data from the Model. It then loads the data and passes it to the Views, and sends the results to the user.

Once we start working with this pattern we will feel how easy it is; it will keep our projects organized. If we need to come back to our project months after finishing it we will appreciate having made it in a structured fashion. No more of—Oh my God where did I put that query, where is that include file?—they will be in the model and the controller respectively.

But, what happens if we want to put our queries in the controller? Well, CodeIgniter allows us to do so (though it is not recommended; if you can avoid, it is better to do so). Other frameworks force you to keep a particular structure, but with CI you can do programming in the way you want. Although it is recommended to keep to the structure, there will be times when we will need to do things the other way. With this structure we can accomplish two important things:

  • Loose Coupling: Coupling is the degree by which the components of a system rely on each other. The less the components depend on each other, the more reusable and flexible the system becomes.
  • Component Singularity: Singularity is the degree by which components have a narrow focus. In CI, each class and its functions are highly autonomous in order to allow maximum usefulness.

But how does all this work?

Now that we have seen how CI is structured, maybe you are asking yourself—how are the files in those three folders (models, views, controllers) working together? To answer this question we have another diagram, here it is:

CodeIgniter 1.7

As you can see it’s similar to the previous one, and a little summarized (but with a wider scope of things, this is how the MVC pattern works), but this time we can see some new elements, and if you look at it closely you will be able to distinguish the flow of data. Let’s explain it, first of all there is a browser call to your site, then the index.php file in the root folder is called (because we removed it from the URL, using the .htaccess file, we don’t see it). This file acts as a router and calls the controllers, as and when they are needed. The controllers, as they are called, come into action. Now, two things can happen:

  • There is no need to fetch data from the database—in this case only the View is called, and loaded by the Controller. Then it is returned to the Browser for you or your visitors to see.
  • There is the need to fetch some data from the database—in this case theController calls the Model, which in turn makes a query to the database. The database returns data to the Model, and the Model to the Controller. The Controller modifies the data in every necessary way. Then it loads the View, passing all necessary data to it, and the View is created and returned to the Browser again.

Do not get confused with the first case; there will be times when you will need to create static pages. CI doesn’t differentiate between static and dynamic pages. On those occasions simply don’t create the Models.

Now, return to our sample site to see how all this applies to it. Remember when we put the URL as http://127.0.0.1/codeigniter, CI’s welcome screen appeared in our browser. Now try this URL http://127.0.0.1/codeigniter/welcome.

You can also try using this URLhttp://127.0.0.1/codeigniter/index.php/welcome.

In both cases the welcome screen appears in the browser. You maybe wondering, how CI knows, if you put http://127.0.0.1/codeigniter/, that it has to load the welcome controller. Don’t worry, we will see that in a moment; for now, we will go on with our example:

http://127.0.0.1/codeigniter/index.php/welcome

A request coming to your web site’s root is intercepted by the index.php file, which acts as a router. That is, it calls a controller—welcome controller—which then returns a view, just as in the previous diagram. But how does the controller do that? We are going to see how in the welcome controller.

The welcome controller

As we know the welcome controller is the default controller, configured in the routes.php file of the config directory and the code is at ./application/controllers/welcome.php. Here’s what it says:

<?php
class Welcome extends Controller
{
function Welcome()
{
parent::Controller();
}
function index()
{
$this->load->view('welcome_message');
}
}
/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */

From the second line you’ll learn that this file is a class. Every controller inherits from an original Controller class, hence extends Controller. The next three lines make the constructor function. Within the class there are two functions or methods—Welcome() and index().

Though it is not necessary, naming controllers the same way as for tables is a good practice. For example, if I have a projects table I will create a projects controller. You can name your controllers the way you want, but naming them like the tables they represent keeps things organized. Also, getting used to this won’t harm you, as other frameworks are stricter about this.

Notice that CI uses the older PHP 4 convention for naming constructor functions, which is also acceptable by PHP 5—it doesn’t require you to use PHP 5 and is happy with either version of the language. The constructor function is used to set up the class each time you instantiate it. We can obviate this and the controller will still work, and if we use it, it won’t do any harm. Inside it we can put instructions to load other libraries or models, or definitions of class variables.

So far the only thing inside the constructor is the parent::Controller(); statement. This is just a way of making sure that you inherit the functionality of the Controller class. If you want to understand the parent CI Controller class in detail, you can look at the file /www/CI_system/libraries/controller.php.

One of the reassuring things about CI is that all the code is there for you to inspect, though you don’t often need to.

Working with views

Let’s go back to the incoming request for a moment. The router needs to know which controller and which function within that controller should handle the request. By default the index function is called if the function is not specified. So, when we put http://127.0.0.1/codeigniter/welcome/, the index function is called. If no error is shown, this function simply loads the view, (‘welcome_message’) using CI’s loader function ($this->load->view). At this stage, it doesn’t do anything cool with the view, such as passing dynamic information to it. That comes in later.

The (‘welcome_message’) it wants to load, is in the views folder that you have just installed at /www/codeigniter/application/views/welcome_message.php. This particular view is only a simple HTML page, but it is saved as a PHP file because most views have PHP code in them (no point in doing all this if we’re only going to serve up plain old static HTML).

Here’s the (slightly shortened) code for the view:

<html>
<head>
<title>Welcome to CodeIgniter</title>
<style type="text/css">
body
{
background-color: #fff;
margin: 40px;
font-family: Lucida Grande, Verdana, Sans-serif;
font-size: 14px;
color: #4F5155;
}
. . . . . more style information here . . . .
</style>
</head>
<body>
<h1>Welcome to CodeIgniter!</h1>
<p>The page you are looking at is being generated dynamically by
CodeIgniter.
</p>
<p>If you would like to edit this page you'll find it located
at:
</p>
<code>system/application/views/welcome_message.php</code>
<p>The corresponding controller for this page is found at:</p>
<code>system/application/controllers/welcome.php</code>
<p>If you are exploring CodeIgniter for the very first time, you
should start by reading the <a href="user_guide/">User
Guide</a>.
</p>
<p><br />Page rendered in {elapsed_time} seconds</p>
</body>
</html>

As you can see, it consists entirely of HTML, with an embedded CSS stylesheet. In this simple example, the controller hasn’t passed any variables to the view.

Curious about—&ltp> &ltbr/> Page rendered in {elapsed_time} seconds </p>? Take a look at: http://codeigniter.com/user_guide/libraries/benchmark.html.

You can name the views the way you want, and don’t put the .php extension for them. You will have to specify the extension when loading them, for example:

$this->load->view('welcome_message.html');

LEAVE A REPLY

Please enter your comment!
Please enter your name here