Navigating Your Site using CodeIgniter 1.7: Part 1

David Upton

November 2009


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.


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, CI's welcome screen appeared in our browser. Now try this URL

You can also try using this URLhttp://

In both cases the welcome screen appears in the browser. You maybe wondering, how CI knows, if you put, 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:

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:

class Welcome extends Controller
function Welcome()
function index()
/* 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, 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:

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

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:

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:


The default controller

A few moments ago we were wondering how it was possible that when we put, the welcome controller was called. Well, no magic there, it is all in /www/codeigniter/application/config/routes.php;open that file and take a look. Read it till you find this line:

$route['default_controller'] = "welcome";

This line tells CI which controller to call, if it is not specified in the URL. Don't misunderstand this, if you pass a wrong URL the default controller won't be called, it's only called if no other controllers are specified. Usually it is used to load the controller that contains the functions that create our index page; after that our application or website will provide our visitors with some kind of navigation.

In this case we are not specifying the function, so the index one will be called, but we could put another one if we want, such as:

$route['default_controller'] = "welcome/myfriend";

In this case we are calling the myfriend function inside the welcome controller. Can you think of more uses of the router file? Let's see one more. Suppose you have a long URL, we are going to use this as an example—

If we add this line of code in the routes.php file:

$route['john'] = "welcome/myfriend/23";

From now on, if you put into your browser you will end up seeing the result of the welcome controller, function myfriend with a parameter with value 23.

As we said, by default, the index function is called if no other is passed. You can alter this default if you like, by including a function called _remap($function). Where $function is the function, in the controller(s), you want to intercept and redirect. The function _remap always gets called first, irrespective of what the URL says.

For example, if we have called and our welcome controller looks this way:

class Welcome extends Controller
function Welcome()
function _remap($method)
if ($method == 'hello')
function say_hello()
echo "Hello";
function index()
/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */

Take this last example as a demonstration of the _remap method. But don't try to use it in a real-world application, as more work needs to be put here.

The _remap function ($method) will be called instead of the hello function passed in the URL. This part of the URL would instead be passed as a parameter to the _remap function. Once inside we can use this parameter in our logic, for example, this time if we receive hello, we call the say_hello function. In other case we call the function passed as a parameter, so if we have the URL, the function say_hello will be called. If we have, then the index function will be called.

Have you noticed the underscore"_" before the function name remap? You can use it in your own functions. This way, they will be only accessible by other functions inside the controller, but not from outside. That said, the following won't work:

CodeIgniter syntax rules

Before we start, let's just summarize the syntax rules that CI uses. The framework expects files to be set up in a certain way, otherwise it may have difficulty indentifying your files properly, or using them.


This is a class (that is OO code). It is called directly by the URL, for example, Controllers are used to call functions by name, for example, mainpage(). However, within a controller you cannot call functions inside another controller. If you need to do such a thing, the functions common to both controllers can be converted into a library or helper.


Controllers begin with class Start extends Controller (where the name of the controller has the first letter in uppercase) and are saved as a .php file in the /system/application/controllers folder. When saved, they should not have the first letter in uppercase, as in start.php and not Start.php. Also, they can include a constructor containing at least:

function Start()

All other code must be written as separate functions within the class, for example, a hello() function.


Views are HTML files that can contain PHP "islands". Here we place all the HTML code needed to create our site's pages. This is what our site's users are going to see. We place all our data, retrieved by our models and prepared by our controllers, here. We can consider the views as the final stage of our data. They are loaded by $this->load->view('testview', $data). Loading and using the view are done in the same action.


The view is written in HTML. The PHP code is included within <?php ?> tags, as with any HTML file. It is saved as a .php file in the views folder.

Types of files or classes on a CI site

There are several sub-folders within the application folder. We have already looked at the controllers, config, and views folders.

But what are libraries, helpers, and plugins? In a technical sense, these folders are treated in much the same way. Let's say that you have written a block of code called display, which contains a function called mainpage. There are four ways you might have done this—as a model, a library, a helper, or a plugin. The following table summarizes the difference between each approach, and shows you how to load and use each type.

File type


How to use it




This is a class (object-oriented or OO code).

Load it like this: $this->load->model('display');

Use it like this: $ this->display->mainpage();

Notes on syntax:

It must begin with class Display extends Model.

It must include a constructor containing at least:

function display()



Also it should contain a separate mainpage() function.

Conceptually: The user guide says, "Models are PHP classes that are designed to work with information in your database".



It is present in both the system and the application folder. Again, this is a class.

Load it like this: $this->load->library('display');

Use it like this: $this->display->mainpage();

Notes on syntax:
No need to extend a base class, or for a constructor function, this is enough:

class Display()

  function mainpage()

      //code here



Conceptually: Intended to hold your own code to extend CI functionality or to create site-specific functionality.



It can be in the system/helpers folder or in the application/helpers folder. This is a script (procedural code, not an OO class).

Load it like this: $this->load->helper('display');

Use a function from it like this: mainpage();

Notes on syntax:

The file should be saved as display_helper.php, that is add _helper to the file name. The function mainpage() should be included in the file, which is simply a collection of separate functions, not a class. As a result you can't directly access CI's other resources any more.

Conceptually: Helpers are intended as a collection of low-level functions to help you perform specific tasks.



It is present in the system/plugins folder but can also be created in an applications/plugins folder. This is a script (not an OO class).

Load it like this: $this->load->plugin('display');

Use a function from it like this: mainpage();

Notes on syntax:

The file should be saved as display_pi.php, that is, add _pi to the end of the filename.

The function mainpage() should be included in the file, which is simply a collection of separate functions, not a class. As a result, you can't directly access CI's other resources any more.

Conceptually: The user guide says, "...the main difference is that a plugin usually provides a single function, whereas a helper is usually a collection of functions....."

You could put your piece of new code in any of these folders, though you'd have to write it as an object-oriented class in the first two cases, as a procedural script in the second, and in the latter cases you wouldn't be able to draw directly on other CI classes.

Though we are not able to directly draw CI resources from within helpers and plugins, there's a way in which we can achieve that, using the get_instance(); method. Take a look at

You'll notice that CI can have two set of helpers, plugins, and libraries, though not of models. There can be one set of each in the application folder, and another set in the system folder. The difference, again, is largely conceptual as explained in the following:

  • Those in the system folder are intended to be part of the core CI code and to be shared by all applications. If you update to a later version of CI, then you will overwrite the system folder and these files may be modified
  • Those in the application folder will only be available to that particular application. If you update to a new version of CI, the application folder will not be overwritten.
  • When you try to load a helper, plugin, or library, CI sensibly looks in both paths. If you attempt to load a library called display, for example, CI will first look in your system/application/libraries directory. If the directory does not exist or the display library is not there, CI will then look in the system/libraries folder.
  • It is possible to effectively overwrite CI's core libraries, helpers, andplugins by introducing your own with the same names in the applications folder. Don't do this accidentally. However, this flexibility is a great advantage for experienced CI users; if you want to extend the basic classes and scripts that come with CI.

In this article, we have covered the following:

  • How MVC helps to organize a dynamic website
  • The process by which CI analyzes an incoming Internet request and decides which part of your code will handle it
  • What the code does
  • CI syntax rules
  • The different type of files or classes you can find—or write for yourself—on a CodeIgniter site

>> Continue Reading Navigating Your Site using CodeIgniter 1.7: Part 2

[ 1 | 2 ]

If you have read this article you may be interested to view :

You've been reading an excerpt of:

CodeIgniter 1.7

Explore Title