Navigating Your Site using CodeIgniter 1.7: Part 1

Exclusive offer: get 50% off this eBook here
CodeIgniter 1.7

CodeIgniter 1.7 — Save 50%

Improve your PHP coding productivity with the free compact open-source MVC CodeIgniter framework!

£14.99    £7.50
by David Upton | November 2009 | MySQL PHP Web Development

In this article series by Jose Argudo Blanco and David Upton, we will cover some important topics, such as the MVC pattern and how CI handles this pattern, and also, we will make an example controller just to see how all this works.
We will briefly look at the theory behind MVC, and then at the way CI organizes itself internally. In particular, what goes in those different folders and how do they communicate?
In this article, we will cover 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

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');
CodeIgniter 1.7 Improve your PHP coding productivity with the free compact open-source MVC CodeIgniter framework!
Published: November 2009
eBook Price: £14.99
Book Price: £24.99
See more
Select your format and quantity:

The default controller

A few moments ago we were wondering how it was possible that when we put http://127.0.0.1/codeigniter/, 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—http://127.0.0.1/codeigniter/welcome/myfriend/23.

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 http://127.0.0.1/codeigniter/john 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 http://127.0.0.1/codeigniter/welcome/hello and our welcome controller looks this way:

<?php
class Welcome extends Controller
{
function Welcome()
{
parent::Controller();
}
function _remap($method)
{
if ($method == 'hello')
{
$this->say_hello();
}
else
{
$this->$method();
}
}
function say_hello()
{
echo "Hello";
}
function index()
{
$this->load->view('welcome_message');
}
/* 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 http://127.0.0.1/codeigniter/welcome/hello, the function say_hello will be called. If we have http://127.0.0.1/codeigniter/welcome/index, 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: http://127.0.0.1/codeigniter/welcome/remap.

CodeIgniter 1.7 Improve your PHP coding productivity with the free compact open-source MVC CodeIgniter framework!
Published: November 2009
eBook Price: £14.99
Book Price: £24.99
See more
Select your format and quantity:

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.

Controller

This is a class (that is OO code). It is called directly by the URL, for example, www.example.com/index.php/start/hello. 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.

Syntax

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()
{
parent::Controller();
}

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

View

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.

Syntax

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

 

Model

 

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()
{

  parent::Model();

}

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".

Library

 

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.

Helper

 

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.

Plugin

 

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 http://codeigniter.com/user_guide/general/creating_libraries.html.

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 :

About the Author :


David Upton

David Upton is a director of a specialized management consultancy company, based in London but working around the world. His clients include some of the world’s largest companies. He is increasingly interested in web-enabling his work, and seeking to turn ideas into robust professional applications by the simplest and easiest route. He has so far written applications for two major companies in the UK. His other interests include simulation, on which he writes a weblog which takes up far too much of his time, and thinking.

Books From Packt

jQuery UI 1.7: The User Interface Library for jQuery
jQuery UI 1.7: The User Interface Library for jQuery

jQuery 1.3 with PHP
jQuery 1.3 with PHP

Symfony 1.3 Web Application Development
Symfony 1.3 Web Application Development

PHP Team Development
PHP Team Development

ICEfaces 1.8: Next Generation Enterprise Web Development
ICEfaces 1.8: Next Generation Enterprise Web Development

Grails 1.1 Web Application Development
Grails 1.1 Web Application Development

Seam 2.x Web Development
Seam 2.x Web Development

Apache MyFaces Trinidad 1.2: A Practical Guide
Apache MyFaces Trinidad 1.2: A Practical Guide

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software