CodeIgniter 1.7

By David Upton , Jose Argudo Blanco
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introduction to CodeIgniter

About this book

CodeIgniter (CI) is a powerful open-source PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit to create full-featured web applications. CodeIgniter is an MVC framework, similar in some ways to the Rails framework for Ruby, and is designed to enable, not overwhelm.

This book explains how to work with CodeIgniter in a clear logical way. It is not a detailed guide to the syntax of CodeIgniter, but makes an ideal complement to the existing online CodeIgniter user guide, helping you grasp the bigger picture and bringing together many ideas to get your application development started as smoothly as possible.

This book will start you from the basics, installing CodeIgniter, understanding its structure and the MVC pattern. You will also learn how to use some of the most important CodeIgniter libraries and helpers, upload it to a shared server, and take care of the most common problems. If you are new to CodeIgniter, this book will guide you from bottom to top. If you are an experienced developer or already know about CodeIgniter, here you will find ideas and code examples to compare to your own.

Publication date:
November 2009
Publisher
Packt
Pages
300
ISBN
9781847199485

 

Chapter 1. Introduction to CodeIgniter

Most of us just want to write applications that work well, and to do it as simply and easily as we can. This book is about CodeIgniter—a tool for making PHP easy to use.

If you need to produce results, have better and more maintainable code, and you enjoy programming, then you should try using CodeIgniter (CI to its friends). CI is free, lightweight, and simple to install, and it really makes your life much easier. Just read this chapter to find out how:

  • What CI can do for you?

  • What is CI? What are Frameworks?

  • Comparing CI to other open source solutions.

  • What CI doesn't do?

What can CodeIgniter do for you?

If you are already writing code in PHP, CI will help you to do it in a better and easier way. It will cut down the amount of code you actually type. Your scripts will be easier to read and update—improving team work and maintainability. It will help you to give large websites a coherent structure. It will discipline your code and make it more robust, in some cases even without your knowing it.

That's quite a big claim. You have already spent some time learning PHP, HTML, CSS, a database, and so on. You need basic, not necessarily expert knowledge of PHP to benefit from CI.

CI is not for you if:

  • You don't have a minimum knowledge of PHP and HTML.

  • You like to write all of your code. There are people who prefer to write their code instead of using already built solutions. If you are that kind of a person, you should try CI. It is very well commented and, if you are short of time, it will help you. You won't need to reinvent the wheel again and again. CI comes with a lot of helpers, libraries, and much more for the most common tasks. Give it a try!

  • You don't like PHP; but how is that possible? With a huge community and hordes of code and tools, PHP is one of the favorite languages of the Web.

  • And definitely CI is not for you if you don't like to finish your projects on time, in a well-structured fashion, and without having to redo the same things again and again.

If you don't belong to any of the categories mentioned in the previous points, keep reading!

Save time

CI doesn't take long to learn, and it quickly pays for your effort in the time saved later. Let's look at a simple measure—how CI cuts down the amount of code you need to type. This is not just good for the lazy. The less you type, the fewer mistakes you make, and the less time you spend debugging your code.

Let's take two examples, (they are explained later in this book, so don't worry now about how they work!). If you are writing a database query, this is how you might write a function within your PHP program to query a MySQL database:

$connection = mysql_connect("localhost","fred","12345");
mysql_select_db("websites", $connection);
$result = mysql_query ("SELECT * FROM sites", $connection);
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
foreach ($row as $attribute)
print "{$attribute[1]}";
}

Now see how a CI function would handle a similar query:

$this->load->database('websites');
$query = $this->db->get('sites');
foreach ($query->result() as $row)
{
print $row->url;
}

Compare the character count—244 for the traditional syntax and 112 for CI. Another thing that you have to take into account when using Active Record is that you can change your database from MySQL to Postgres (or any other that is supported by CI) and you won't need to change your queries—a very helpful thing.

Now let's take an example where you are writing a data entry form in HTML, and you want a drop-down query box. Let's say this drop-down query box shows three options and allows the user to select one of them. In HTML, a drop-down box can be created like this:

<select name="url">
<option value="this">www.this.com</option>
<option value="that">www.that.com</option>
<option value="theother" selected>www.theother.com</option>
</select>

CI's version is both shorter and, because it works from an array, more adapted to PHP processing:

$urlarray = array(
'this' => 'www.this.com',
'that' => 'www.that.com',
'theother' => 'www.theother.com',
);
$variable = form_dropdown('url', $urlarray, 'this');

In HTML, you need to type 154 characters, and 128 in CI. Note how easily we can define the "selected" element of the drop-down menu, putting it in the third parameter. This thing alone will save us a lot of time.

Make your site more robust

Although you don't need to write much code, CI provides a lot of the standard functionality and better security, and it remembers all those oddities and quirks. It keeps track of things you may have forgotten about (those little touches that distinguish amateur sites from professional ones).

Keep your links up-to-date automatically

Suppose you've just written a menu page, with lot of hyperlinks to other pages in your site. They are all in the traditional HTML format as shown:

<a href="http://www.mysite.com/index.php/start/hello/fred
">say hello to Fred</a>

Then, you decide to move the site to another URL. That means you have to go painstakingly through your code, looking for each URL, and rewriting it, else none of your links will work.

CI gives you a simple function to write hyperlinks like this:

echo anchor('start/hello/fred', 'Say hello to Fred');

CI also encourages you to put the URL of your site in a configuration file that the rest of your site can access. CI's anchor function that we've used here, automatically refers to that configuration file. So, when you come to move your site, you only need to change that one entry in the configuration file, and all your hyperlinks are updated automatically.

Preventing database SQL injection attacks and form prepping

Data entry is fraught with problems. There are certain limitations of HTML and databases, as a result of which data containing symbols such as apostrophes and quotation marks may not be saved correctly, or even worse, your database may be open to malicious attacks.

For example, take this query:

SELECT id, name FROM users WHERE user = '{$user}' AND password = '{$password}';

Consider that the variables have the following values:

$user = "Fred";
$password = "1234";

Now our query would translate to:

SELECT id, name FROM users WHERE user = 'Fred' AND password = '1234';

This query will return a good result, but, what if our variables were:

$user = "Fred";
$password = "1234' OR '1' = '1";

Now our query would produce:

SELECT id, name FROM users WHERE user = 'Fred' AND password = '1234' OR '1' = '1';

This time the variable's data contains a new "where" clause with a condition that is always true. The user inserts some characters, such as " ' " to make our query behave in a way we don't want, and give bad results. It's easy to see that with this kind of attacks more than just giving bad results can be achieved, dropping tables being one of the worse things. These problems don't always come in the shape of SQL injection attacks; most of the time not prepping data correctly would bring problems too, for example:

$user = "Fred";
$password = "12xWgBq'wS";

Our password variable contains a password that looks quite secure, but will produce a problem in our query:

SELECT id, name FROM users WHERE user = 'Fred' AND password = '12xWgBq'wS';

The data will cut the query, producing some errors when executed. What can we do to prevent these problems? Well the answer to this is to prepare or "prep" our data in our data entry form, before it is submitted to the database. All this takes time and a certain amount of extra coding.

CI's form helper does this, automatically. So, when you create an input box by typing:

echo form_input('user', 'Fred');

You're also getting the hidden benefit of:

function form_prep($str = '')
{
// if the field name is an array we do this recursively
if (is_array($str))
{
foreach ($str as $key => $val)
{
$str[$key] = form_prep($val);
}
return $str;
}
if ($str === '')
{
return '';
}
$temp = '__TEMP_AMPERSANDS__';
// Replace entities to temporary markers so that
// htmlspecialchars won't mess them up
$str = preg_replace("/&(\d+);/", "$temp\\1;", $str);
$str = preg_replace("/&(\w+);/", "$temp\\1;", $str);
$str = htmlspecialchars($str);
// In case htmlspecialchars misses these.
$str = str_replace(array("'", '"'), array("'", "&quot;"),
$str);
// Decode the temp markers back to entities
$str = preg_replace("/$temp(\d+);/","&\\1;",$str);
$str = preg_replace("/$temp(\w+);/","&\\1;",$str);
return $str;
}

This is the code that handles special characters such as "&" so that they don't cause confusion while your form is being submitted. As you can see, there is some quite tricky regex code in there.

Possibly you like typing regexes. Some people like lying on a bed of nails, some like listening to ABBA; it's a free country. If you don't like these things, you can let CI do them for you (the regexes, not ABBA), and you needn't even be aware of the code that's working in the background for you, every time you write that one simple line of code:

echo form_input('user', 'Fred');

Besides this, CI's Active Record class automatically escapes special characters in database queries; this can also be achieved with query bindings, to give some extra automatic protection to your site; without our doing anything CI is helping us to make our site more secure.

Protect your site from XSS attacks

As stated on Wikipedia (http://en.wikipedia.org/wiki/Cross-site_scripting), XSS (cross site scripting) is a kind of vulnerability that allows some unwanted code to be executed in our application, phising attacks, data theft, and more. In order to avoid this you should validate your data.

CodeIgniter helps you to do so, in all your applications if you set global XSS filter to true in your configuration file, or whenever you need it:

$data = $this->input->xss_clean($data);

You can even use it to check potential XSS attacks within image files:

$this->input->xss_clean($file, TRUE);

The second parameter tells CI that it is an image that needs validation.

Make your code bolder

CI also makes it easy to do things you might not have tried before. Of course, PHP users can always integrate libraries from PHP Extension and Application Repository (PEAR) and other sources. They aren't always easy to integrate, or use, and their syntax and standards differ greatly. CI has a common set of standards, and once you've mastered its syntax, all its parts work together without complication. All its code is well-written and reliable, and is tested by its user community. It puts much more sophistication in your hands.

Let's take a look at two examples to illustrate this point.

Send email attachments without hassles

Sending emails is a complex business. CI's code for doing it looks easy to follow:

$this->load->library('email');
$this->email->from('[email protected]', 'Your Name');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$this->email->send();

There are a number of issues involved in sending emails—setting word wrapping and escaping it (so that long URLs don't get wrapped and broken up). For example, when sending attachments, the standard PHP functions can get quite complex. As a result many code writers are tempted to avoid using these functions if possible.

CI's email class makes it simple to send an attachment. You write:

$this->email->attach('path/to/photo1.jpg');

CI does the rest, working behind the scenes. There is a function that sorts out MIME types for nearly a hundred type of attachments. So it knows that your photo, photo1.jpg, is an image/jpeg MIME type. It remembers to generate boundary delimiters in the right places around your attachments. It takes care of wrapping your text, and it allows you to easily mark chunks of text you don't want wrapped.

Save bandwidth by zipping files that users need to download

To save bandwidth, it's a fairly common practice to compress or zip files before you download them. That's something you might have never done, and you wouldn't know how to go about it. On the other hand, CI has a nice facility that allows you to produce ZIP files with four lines of code:

$name = 'mydata1.txt';
$data = 'the contents of my file…………';
$this->zip->add_data($name, $data);
$this->zip->archive('c:/my_backup.zip');

Run this snippet, and you will find a ZIP archive on your C: drive containing one file. Your ZIP file reader will unzip it and produce the original data for you. People who use your site won't know that you've produced this impressive result so easily. They'll be impressed! Your site will save bandwidth. You did it in minutes rather than hours.

 

What can CodeIgniter do for you?


If you are already writing code in PHP, CI will help you to do it in a better and easier way. It will cut down the amount of code you actually type. Your scripts will be easier to read and update—improving team work and maintainability. It will help you to give large websites a coherent structure. It will discipline your code and make it more robust, in some cases even without your knowing it.

That's quite a big claim. You have already spent some time learning PHP, HTML, CSS, a database, and so on. You need basic, not necessarily expert knowledge of PHP to benefit from CI.

CI is not for you if:

  • You don't have a minimum knowledge of PHP and HTML.

  • You like to write all of your code. There are people who prefer to write their code instead of using already built solutions. If you are that kind of a person, you should try CI. It is very well commented and, if you are short of time, it will help you. You won't need to reinvent the wheel again and again. CI comes with a lot of helpers, libraries, and much more for the most common tasks. Give it a try!

  • You don't like PHP; but how is that possible? With a huge community and hordes of code and tools, PHP is one of the favorite languages of the Web.

  • And definitely CI is not for you if you don't like to finish your projects on time, in a well-structured fashion, and without having to redo the same things again and again.

If you don't belong to any of the categories mentioned in the previous points, keep reading!

Save time

CI doesn't take long to learn, and it quickly pays for your effort in the time saved later. Let's look at a simple measure—how CI cuts down the amount of code you need to type. This is not just good for the lazy. The less you type, the fewer mistakes you make, and the less time you spend debugging your code.

Let's take two examples, (they are explained later in this book, so don't worry now about how they work!). If you are writing a database query, this is how you might write a function within your PHP program to query a MySQL database:

$connection = mysql_connect("localhost","fred","12345");
mysql_select_db("websites", $connection);
$result = mysql_query ("SELECT * FROM sites", $connection);
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
foreach ($row as $attribute)
print "{$attribute[1]}";
}

Now see how a CI function would handle a similar query:

$this->load->database('websites');
$query = $this->db->get('sites');
foreach ($query->result() as $row)
{
print $row->url;
}

Compare the character count—244 for the traditional syntax and 112 for CI. Another thing that you have to take into account when using Active Record is that you can change your database from MySQL to Postgres (or any other that is supported by CI) and you won't need to change your queries—a very helpful thing.

Now let's take an example where you are writing a data entry form in HTML, and you want a drop-down query box. Let's say this drop-down query box shows three options and allows the user to select one of them. In HTML, a drop-down box can be created like this:

<select name="url">
<option value="this">www.this.com</option>
<option value="that">www.that.com</option>
<option value="theother" selected>www.theother.com</option>
</select>

CI's version is both shorter and, because it works from an array, more adapted to PHP processing:

$urlarray = array(
'this' => 'www.this.com',
'that' => 'www.that.com',
'theother' => 'www.theother.com',
);
$variable = form_dropdown('url', $urlarray, 'this');

In HTML, you need to type 154 characters, and 128 in CI. Note how easily we can define the "selected" element of the drop-down menu, putting it in the third parameter. This thing alone will save us a lot of time.

Make your site more robust

Although you don't need to write much code, CI provides a lot of the standard functionality and better security, and it remembers all those oddities and quirks. It keeps track of things you may have forgotten about (those little touches that distinguish amateur sites from professional ones).

Keep your links up-to-date automatically

Suppose you've just written a menu page, with lot of hyperlinks to other pages in your site. They are all in the traditional HTML format as shown:

<a href="http://www.mysite.com/index.php/start/hello/fred
">say hello to Fred</a>

Then, you decide to move the site to another URL. That means you have to go painstakingly through your code, looking for each URL, and rewriting it, else none of your links will work.

CI gives you a simple function to write hyperlinks like this:

echo anchor('start/hello/fred', 'Say hello to Fred');

CI also encourages you to put the URL of your site in a configuration file that the rest of your site can access. CI's anchor function that we've used here, automatically refers to that configuration file. So, when you come to move your site, you only need to change that one entry in the configuration file, and all your hyperlinks are updated automatically.

Preventing database SQL injection attacks and form prepping

Data entry is fraught with problems. There are certain limitations of HTML and databases, as a result of which data containing symbols such as apostrophes and quotation marks may not be saved correctly, or even worse, your database may be open to malicious attacks.

For example, take this query:

SELECT id, name FROM users WHERE user = '{$user}' AND password = '{$password}';

Consider that the variables have the following values:

$user = "Fred";
$password = "1234";

Now our query would translate to:

SELECT id, name FROM users WHERE user = 'Fred' AND password = '1234';

This query will return a good result, but, what if our variables were:

$user = "Fred";
$password = "1234' OR '1' = '1";

Now our query would produce:

SELECT id, name FROM users WHERE user = 'Fred' AND password = '1234' OR '1' = '1';

This time the variable's data contains a new "where" clause with a condition that is always true. The user inserts some characters, such as " ' " to make our query behave in a way we don't want, and give bad results. It's easy to see that with this kind of attacks more than just giving bad results can be achieved, dropping tables being one of the worse things. These problems don't always come in the shape of SQL injection attacks; most of the time not prepping data correctly would bring problems too, for example:

$user = "Fred";
$password = "12xWgBq'wS";

Our password variable contains a password that looks quite secure, but will produce a problem in our query:

SELECT id, name FROM users WHERE user = 'Fred' AND password = '12xWgBq'wS';

The data will cut the query, producing some errors when executed. What can we do to prevent these problems? Well the answer to this is to prepare or "prep" our data in our data entry form, before it is submitted to the database. All this takes time and a certain amount of extra coding.

CI's form helper does this, automatically. So, when you create an input box by typing:

echo form_input('user', 'Fred');

You're also getting the hidden benefit of:

function form_prep($str = '')
{
// if the field name is an array we do this recursively
if (is_array($str))
{
foreach ($str as $key => $val)
{
$str[$key] = form_prep($val);
}
return $str;
}
if ($str === '')
{
return '';
}
$temp = '__TEMP_AMPERSANDS__';
// Replace entities to temporary markers so that
// htmlspecialchars won't mess them up
$str = preg_replace("/&(\d+);/", "$temp\\1;", $str);
$str = preg_replace("/&(\w+);/", "$temp\\1;", $str);
$str = htmlspecialchars($str);
// In case htmlspecialchars misses these.
$str = str_replace(array("'", '"'), array("'", "&quot;"),
$str);
// Decode the temp markers back to entities
$str = preg_replace("/$temp(\d+);/","&\\1;",$str);
$str = preg_replace("/$temp(\w+);/","&\\1;",$str);
return $str;
}

This is the code that handles special characters such as "&" so that they don't cause confusion while your form is being submitted. As you can see, there is some quite tricky regex code in there.

Possibly you like typing regexes. Some people like lying on a bed of nails, some like listening to ABBA; it's a free country. If you don't like these things, you can let CI do them for you (the regexes, not ABBA), and you needn't even be aware of the code that's working in the background for you, every time you write that one simple line of code:

echo form_input('user', 'Fred');

Besides this, CI's Active Record class automatically escapes special characters in database queries; this can also be achieved with query bindings, to give some extra automatic protection to your site; without our doing anything CI is helping us to make our site more secure.

Protect your site from XSS attacks

As stated on Wikipedia (http://en.wikipedia.org/wiki/Cross-site_scripting), XSS (cross site scripting) is a kind of vulnerability that allows some unwanted code to be executed in our application, phising attacks, data theft, and more. In order to avoid this you should validate your data.

CodeIgniter helps you to do so, in all your applications if you set global XSS filter to true in your configuration file, or whenever you need it:

$data = $this->input->xss_clean($data);

You can even use it to check potential XSS attacks within image files:

$this->input->xss_clean($file, TRUE);

The second parameter tells CI that it is an image that needs validation.

Make your code bolder

CI also makes it easy to do things you might not have tried before. Of course, PHP users can always integrate libraries from PHP Extension and Application Repository (PEAR) and other sources. They aren't always easy to integrate, or use, and their syntax and standards differ greatly. CI has a common set of standards, and once you've mastered its syntax, all its parts work together without complication. All its code is well-written and reliable, and is tested by its user community. It puts much more sophistication in your hands.

Let's take a look at two examples to illustrate this point.

Send email attachments without hassles

Sending emails is a complex business. CI's code for doing it looks easy to follow:

$this->load->library('email');
$this->email->from('[email protected]', 'Your Name');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$this->email->send();

There are a number of issues involved in sending emails—setting word wrapping and escaping it (so that long URLs don't get wrapped and broken up). For example, when sending attachments, the standard PHP functions can get quite complex. As a result many code writers are tempted to avoid using these functions if possible.

CI's email class makes it simple to send an attachment. You write:

$this->email->attach('path/to/photo1.jpg');

CI does the rest, working behind the scenes. There is a function that sorts out MIME types for nearly a hundred type of attachments. So it knows that your photo, photo1.jpg, is an image/jpeg MIME type. It remembers to generate boundary delimiters in the right places around your attachments. It takes care of wrapping your text, and it allows you to easily mark chunks of text you don't want wrapped.

Save bandwidth by zipping files that users need to download

To save bandwidth, it's a fairly common practice to compress or zip files before you download them. That's something you might have never done, and you wouldn't know how to go about it. On the other hand, CI has a nice facility that allows you to produce ZIP files with four lines of code:

$name = 'mydata1.txt';
$data = 'the contents of my file…………';
$this->zip->add_data($name, $data);
$this->zip->archive('c:/my_backup.zip');

Run this snippet, and you will find a ZIP archive on your C: drive containing one file. Your ZIP file reader will unzip it and produce the original data for you. People who use your site won't know that you've produced this impressive result so easily. They'll be impressed! Your site will save bandwidth. You did it in minutes rather than hours.

 

What CI doesn't do


There are some things that CI doesn't do. CI was intended to be a small and lightweight framework. The zipped download for version 1.7.2 is only 2.1 MB and is downloaded in seconds, whereas the Zend framework is 10 MB. It won't answer all the problems you will have. But it does:

  • Make it easy and quick to program in PHP

  • Structure your site and help you through the architectural decisions

As a result of being lightweight, it does not have as many features as some of its rivals. Other frameworks such as Rails, CakePHP, or Symfony have scaffolding and generators. These tools automatically write certain basic scripts for you.

Once you have set up a database, Rails creates out-of-the-box web pages to do basic Create, Read, Update, and Delete (CRUD) operations on the database tables. In addition, Rails allows you to write generators—pieces of code that automatically write other basic scripts. The Rails community has created quite a lot of these, so you can automatically generate scripts that do all sorts of clever things.

CI concentrates on making basic things easy. Some of the things it handles are:

  • Session management and cookies (see Chapter 6)

  • Database access and queries (see Chapter 4)

  • Building HTML stuff, like pages and forms, and validating form entries (see Chapter 5)

  • Communicating on the Internet, using FTP (Chapter 9)

Sounds familiar? All of these are basic processes, which you will have to go through if you're building a dynamic website. CI makes these processes easier, and makes your code more likely to work. Join this outstanding community; it will help you in case you need it (at the CodeIgniter forums). You can even share code at the Wiki (http://codeigniter.com/wiki/), and you will find why CI is so popular.

 

Yes, but…what is CodeIgniter? What are frameworks?


Shortly after programming was invented, it was noticed that it involved many repetitive operations. And maybe shortly after that, Ada Lovelace—spanner in hand adjusting Babbage's differential engine—or Alan Turing at Bletchley Park decided to modularize code. So, you only had to write certain chunks once, and could then reuse them. PHP programmers are used to writing separate chunks of code in functions, and then storing those functions in include files.

At one level, a framework is just that—lot of chunks of code stored in separate files, which simplify the coding of repetitive operations. In the previous examples, connecting to the database or building HTML form elements are abstracted and simplified for you. You call a function in the framework, which is easy to handle than the original code.

It goes beyond that. Writing code involves continuous choices between the many ways of tackling the same problem. Most frameworks impose a set of choices on you. They've started to handle the problem one way, so you have to go that way as well. If they are sensible choices, it makes your life much simpler. If not, it's like trying to write a sales brochure using Excel, or showing cash flow projections using Word. Both can probably be done, but neither is the best use of your time.

Sensible design decisions make sure that the things you need are accessible, but prevent them from spilling over into each other. A good framework makes these decisions for you—starting off with a sensible foundation for your program and guiding you through the next steps.

A framework will also improve team programming. As every developer has to adhere to the framework syntax and structure, it is an important part of software maintainability. The code you write today needs to be readable by other people in future. Imagine you arrive to a new workplace and then you inherit a couple of projects. In a perfect world those projects would be well commented, but reality usually hits... Wouldn't it be nice to have a central resource of documentation to get started with those projects?

Most frameworks will offer good documentation. CI isn't an exception; everything is well documented—functions, structures, conventions. You won't have to imagine what a certain function does, you will know it. A very good starting point, don't you think?

Nowadays there are lot of frameworks out there, not only PHP frameworks but Ruby frameworks, Python frameworks, and so on. For PHP programmers there are hundreds of options (well, may not be hundreds, but if we do search for PHP frameworks the results will be overwhelming). Of all these options there are some that are more popular; CI is among them, with others such as CakePHP, Zend Framework, Symfony, and more.

As you are reading this book, you are interested in PHP frameworks, especially CodeIgniter, so we will keep to it.

If you take a look at http://phpframeworks.com/ and http://www.phpframeworks.com/top-10-php-frameworks/, you will see how well CodeIgniter is doing. CI is very popular as a PHP framework; with this book you will know, why. Also if you look at some forums and blogs you'll notice that postings get very heated about which framework is the best. The truth seems to be that each has its strengths, and none is without its own weaknesses. In time you will learn to decide which framework to use in which project. It is recommended that you should think about which tool to use, before starting your projects. Choose the one that will help you to end with a well done project, in good time, and with the best possible scalability. Most of the times CI helps achieve this.

 

Comparing CI to other open source solutions (CakePHP and Joomla!)


For one reason or another one should compare these three most of the time and, of course, use one of them. There are other solutions out there, as we have commented before, "few" is not the word to describe PHP frameworks.

Though you would like to have Zend Framework and Symfony in your toolbox, for now, let's use these three for comparison. For example, when Jose heard about frameworks it was all about Ruby on Rails. Before that he used to write his own code for every project. Though Ruby on Rails is a very good framework, for him—a PHP programmer at heart—that was not the solution.

Searching for a PHP framework that was similar to Ruby on Rails, but PHP made, CakePHP was one option. It was quite similar in concept to Ruby on Rails, it also had the same convention-driven architecture that you need to learn before using it. It will pay-back with lots of functionality, automation, and more. But keep in mind that the learning curve is steeper than CodeIgniter's.

Using CakePHP requires you to adhere to some strict conventions (those can be changed but the out-of-the-box software comes with them). Most of the time they are naming conventions, but there are database conventions also.

After some time, because of curiosity, in spite of incredible lack of learning time (some nearby shouting boss also helped), continuing research of PHP frameworks found CodeIgniter. The most convincing thing was the documentation (CakePHP wasn't as well documented as it is today).

CI has less conventions, and minimal configuration, also you can forget about most of them and work as you have always done. You don't want to use models, and you don't have to (though it is recommended). That said, one of the strengths of CI is just that—download it and start programming.

Joomla! is not exactly a framework, it helps you build websites faster. Also in the latest versions it has turned into the MVC (Model-View-Controller) pattern. The good part of Joomla! is that it is a CMS (Content Management System), but I think it is also its bad part, as sometimes you just don't need so much as Joomla! has to offer. Of course you can develop your own solution over Joomla!, but then what's the point of using Joomla!, and not using what it has to offer?

CI, usually, is the most well-balanced of the three, but let's see how we can choose one of them.

What to choose

With all those options out there, why should you go with CI? The answer—it's not that easy and involves, in most cases, personal preference. There will be projects that will be better suited to one of the other two options. Let's see some examples that will guide us.

When to choose Joomla!

  • If we need a CMS (it may sound redundant, but...).

  • If there is already a component, module, or some other functionality that we need, then there is something built that can help us carry out the project in no time.

  • If the client asks you to use it. Joomla! is a well known software, and sometimes your client can just ask you to use it.

When to choose CakePHP

  • If there are lot of relations between database tables. Cake's Active Record capabilities are slightly more powerful than CI's.

  • If you need to build some admin zone quickly. Cake's bake script can read your database and build some CRUD (Create, Read, Update, Delete) pages for your tables.

When to choose CodeIgniter

  • If the project doesn't have or doesn't need a very rigid structure. Also CI is good for working with legacy code.

  • If you need to start programming right away, without having to learn a lot of conventions.

  • If you need some software that helps you, with the confidence that it will help you in the way you really need, and learn the way something needs to be done.

  • If you know PHP, you can use CI.

  • The client needs some solution built specifically for him/her, and not an adapted solution (that would be in case of some Joomla! components/modules).

Most of the time we will be using CI because it is very flexible. If you like programming CI will help you in doing it. It will seem as if CI isn't even there. You realize it only when you look at the time you are gaining and the better structure of your project.

If you are new to frameworks it is recommended that you get CI, maybe later you use another one (probably both of them), but CI will always have a place in your heart.

Note

Packt Publishing has books on some other frameworks and Joomla!. It is recommended to read them, it will give you a broader view of things.

For books on Joomla visit http://www.packtpub.com/joomla-version-1-5/book.

For books on CakePHP visit http://www.packtpub.com/cakephp-application-development/book.

 

License


If you are building a commercial application, the license terms for any software you are using become critical. If you are raising venture capital, expect the VC's lawyers to go over them in detail. With CI this is not a problem. It has a very generous license that is downloaded with your files.

Unlike some commercial software, CI's license even fits on one screen. Here it is, in the following screenshot:

 

Summary


If you already know some PHP and are designing intelligent websites, the CodeIgniter framework is all about making your life easier. It helps you to:

  • Save time

  • Make your site more robust

  • Achieve more sophisticated coding

  • It makes coding fun again, rather than a chore

There are quite a lot of frameworks and all of them offer chunks of pre-written code that make the repetitive or complex processes of coding easier and not just for the PHP language. They impose a helpful structure on your site's development.

This book does not make any comparisons between frameworks. CI works for most, and we will see, how and why. It will be useful for you too, and you will be able to save much time and, as a result, enjoy the coding process more.

This book takes you through some of the framework's main features, and tries to explain some of what goes on "under the hood". We've used a real-world example for the code illustrations in this book to show that CI is a serious tool that can be quickly and easily used in a demanding environment.

Enjoy!

About the Authors

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

    Browse publications by this author
  • Jose Argudo Blanco

    Jose Argudo Blanco is a web developer from Valencia, Spain. After finishing his studies he started working for a web design company. After working for six years for that company and some others, he decided to work as a freelance.

    Now, after some years have passed, he thinks it's the best decision he has ever takena decision that let him work with the tools he likes, such as CodeIgniter, Joomla!, CakePHP, JQuery, and other well-known open source technologies.

    For the past few months he has also reviewed some books for Packt Publishing, such as Magento 1.3 Theme Design, Magento: Beginner's Guide, Joomla! 1.5 SEO, Symfony 1.3 Web Application Development, and Joomla! with Flash. The one yet to be published is Magento Development with PHP.

    Browse publications by this author
Book Title
Unlock this book and the full library for FREE
Start free trial