Login

Introduction to the CodeIgniter PHP Framework

In this group of articles, I’ll be taking a close look at the main features bundled with the CodeIgniter PHP framework. With it, you can quickly build small to moderate object-oriented applications. Now, it’s time to begin harnessing the real power of CodeIgniter. Ignite yourself and start reading now!

Building web applications with PHP is a pretty simple process. As a PHP developer, you can develop practically anything, including database abstraction layers, form validation programs, file upload applications, and so forth. The list goes on and on.

Once you’ve mastered the foundations of the object-oriented paradigm and learned how to implement certain common design patterns in real-world conditions, you should be armed with a useful toolkit comprised of all sorts of classes and functions that can be used any number of times.

Although you may not be aware of this fact, your toolkit can be considered a general PHP development framework. The end result of your own efforts and skills as programmer.

However, there are certain situations when the capabilities offered by your own framework simply aren’t good enough to fit the requirements of a particular application. In a case like this, you can either upgrade your framework, which will probably require coding additional classes and functions, or you can pick up a third-party software from the numerous packages available on the web today.

If you choose the latter, then you’ll be confronted with another challenge that will keep your mind spinning in circles. Should I pick up a full-featured framework like Zend, or should I work with a more approachable solution, like CakePHP or WACT?

Actually, the answer to that question depends strongly on what type of project you’re going to develop and how much time you want to spend configuring and learning how to use a particular framework. For instance, Zend is great for building enterprise-level PHP applications, but it’s likely that you’ll find it pretty overwhelming to work with at first.

On the other hand, CakePHP can be much easier to set up and use, even though they’re not loaded with all the features offered by Zend. However, in the last few months, a small framework has gained popularity with many PHP programmers due to its ultra-fast learning curve and easy configuration.

Actually, I’m talking about CodeIgniter (http://codeigniter.com), a solid piece of software written by Rick Ellis in PHP 4. It permits users to develop small and middle-scale PHP applications in minutes (literally) with minimal setup. In addition, CodeIgniter is built around the Model-View-Controller pattern, which allows you to easily separate data from application logic and visual presentation.

{mospagebreak title=Start using CodeIgniter}

Obviously, the first step that you should take before using Code Igniter is installing its source files into your test web server. To do so, simply point your browser to the following url: http://codeigniter.com/downloads/. Download the ZIP file that contains these files.

Once you’ve accomplished this, unzip the package and upload its folders and files to a chosen directory of your web server. In my personal case, I saved it to a “/codeigniter/” directory under the server’s root, but you may want to select a different location.

Finally, navigate to the application/config/config.php file, then open it with your code editor and configure the following array settings, as shown below:

|————————————————————————–

| Base Site URL

|————————————————————————–

$config[‘base_url’] = "http://127.0.0.1/codeigniter/";

|————————————————————————–

| Index File

|————————————————————————–

$config[‘index_page’] = "index.php";

|————————————————————————–

| Default Language

|————————————————————————–

$config[‘language’] = "english";

|————————————————————————–

| Default Character Set

|————————————————————————–

$config[‘charset’] = "UTF-8";

|————————————————————————–

| Cache Directory Path

|————————————————————————–

$config[‘cache_path’] = ‘http://127.0.0.1/codeigniter/cache/’;

|————————————————————————–

| Session Variables

|————————————————————————–

$config[‘sess_cookie_name’] = ‘ci_session’;

$config[‘sess_expiration’] = 7200;

$config[‘sess_encrypt_cookie’] = FALSE;

$config[‘sess_use_database’] = FALSE;

$config[‘sess_table_name’] = ‘ci_sessions’;

$config[‘sess_match_ip’] = FALSE;

$config[‘sess_match_useragent’] = TRUE;

$config[‘sess_time_to_update’] = 300;

|————————————————————————–

| Global XSS Filtering

|————————————————————————–

$config[‘global_xss_filtering’] = FALSE;

|————————————————————————–

| Output Compression

|————————————————————————–

$config[‘compress_output’] = TRUE;

|————————————————————————–

| Rewrite PHP Short Tags

|————————————————————————–

$config[‘rewrite_short_tags’] = FALSE;

As you can see, the above settings provide Code Igniter with crucial information about your web applications, including the base url of your site, the default language and character set, and the index file that will be utilized. Also, it’s possible to specify whether any output generated by an application should be filtered to prevent XSS attacks, and whether it should be cached and compressed previously.

Finally, there’s a number of simple options that tell Code Igniter how to handle session data. They are actually fairly easy to configure. Although, you should pay special attention to the following entries:

$config[‘sess_use_database’] = FALSE;

$config[‘sess_table_name’] = ‘ci_sessions’;

If a value of “TRUE” is assigned to the first array element, then Code Igniter will store all of your session data in a MySQL database table, whose name will be specified in the second entry. In this case, a FALSE value has been assigned to the first setting, meaning that session data will be saved to a temporary directory in the web server.

Lastly, it’s possible to configure whether the use of short PHP tags will be enabled within view files. This is something that will be discussed in more detail when I develop some sample applications for you. For now, I’ll keep this option disabled.

So far, so good. I showed how to configure the main entries of Code Igniter’s config.php file. Of course, when you edit the file in question, you’ll see that it contains a few additional settings. However, to keep things rather simple, I’m going to use only the ones discussed above.

Now that the “config.php” file has been properly setup, it’s time to move on and learn how to configure an additional file, which is located at /config/database.php and is used by Code Igniter when working with MySQL databases.

To see how this database file will be edited, please click on the link below and read the following section.

{mospagebreak title=Activating support for MySQL databases}

As I said previously, the last file that you’ll need to edit is the one located at /config/database.php. Open it and assign the correct values to the following settings:

$active_group = "default";

$active_record = TRUE;

$db[‘default’][‘hostname’] = "localhost";

$db[‘default’][‘username’] = "root";

$db[‘default’][‘password’] = "mypassword";

$db[‘default’][‘database’] = "mydatabase";

$db[‘default’][‘dbdriver’] = "mysql";

$db[‘default’][‘dbprefix’] = "";

$db[‘default’][‘pconnect’] = TRUE;

$db[‘default’][‘db_debug’] = TRUE;

$db[‘default’][‘cache_on’] = FALSE;

$db[‘default’][‘cachedir’] = "";

$db[‘default’][‘char_set’] = "utf8";

$db[‘default’][‘dbcollat’] = "utf8_general_ci";

As you can see, all of the above entries are self explanatory, since they’re used by Code Igniter to connect to MySQL and select a particular database, which you’ve probably done hundreds of times before.

However, in this case it’s possible to work with several sets of connection values. Suppose for a moment that you need to use multiple development environments with a shared web server. In that case you might want to create a connection group for each of these environments in the following way:

$db[‘default’][‘hostname’] = "localhost";

$db[‘default’][‘username’] = "root";

$db[‘default’][‘password’] = "mypassword";

$db[‘default’][‘database’] = "mydatabase";

$db[‘default’][‘dbdriver’] = "mysql";

$db[‘default’][‘dbprefix’] = "";

$db[‘default’][‘pconnect’] = TRUE;

$db[‘default’][‘db_debug’] = FALSE;

$db[‘default’][‘cache_on’] = FALSE;

$db[‘default’][‘cachedir’] = "";

$db[‘default’][‘char_set’] = "utf8";

$db[‘default’][‘dbcollat’] = "utf8_general_ci";

$db[‘production’][‘hostname’] = "localhost";

$db[‘ production’][‘username’] = "root";

$db[‘ production’][‘password’] = "myotherpassword";

$db[‘ production’][‘database’] = "myotherdatabase";

$db[‘ production’][‘dbdriver’] = "mysql";

$db[‘ production’][‘dbprefix’] = "";

$db[‘ production’][‘pconnect’] = TRUE;

$db[‘ production’][‘db_debug’] = FALSE;

$db[‘ production’][‘cache_on’] = FALSE;

$db[‘ production’][‘cachedir’] = "";

$db[‘ production’][‘char_set’] = "utf8";

$db[‘ production’][‘dbcollat’] = "utf8_general_ci";

See how easy it is to set up two sets of MySQL connections for different development environments? I hope you do!

Finally, the “active_record” entry should be activated when accessing MySQL database tables using the homonymous pattern. Actually, Code Igniter comes bundled with a bunch of methods that allow you to handle MySQL data via the active record approach. However, this topic will be covered in upcoming tutorials of this series, therefore, this option will be left enabled.

So far, these are all the array entries that you’ll need to edit in the “database.php” file in order to activate the support for MySQL databases. At this stage, everything has been properly setup to start developing object-oriented applications with Code Igniter!

In the section to come I’ll be showing you how to build a simple PHP program that uses the Model-View-Controller pattern in order to display a trivial message on the browser.

To learn how this initial sample application will be developed, click on the link below and keep reading.

{mospagebreak title=Developing the first application with Code Igniter}

As I mentioned in the introduction, Code Igniter uses the Model-View-Controller pattern to build web applications. This comes in handy for separating business and application logic from the visual presentation. Thus, since I plan to develop a simple application that will display a simple message on the screen, the first thing that I’m going to do is define the corresponding controller class.

To do this, I’ll create a class called “HelloWorld,” which will be saved to the /system/application/controllers/ folder as “helloworld.php." The signature of this sample class looks like this:

<?php

class HelloWorld extends Controller{

function HelloWorld(){

// load controller parent

parent::Controller();

}

function index(){

$data[‘title’]=’My first application created with Code Igniter’;

$data[‘message’]=’Hello world!’;

// load ‘helloworld’ view

$this->load->view(‘helloworld’,$data);

}

}

?>

Now that you know how the “HelloWorld” controller class looks, it’s necessary to dissect it in different parts and explain the functionality. In the first place, you should notice that each time a new controller is created, it must extend the default controller provided by Code Igniter. Therefore, this sample class is defined as a subclass of this controller.

Then, this sample class loads the parent’s constructor and then defines a brand new method called “index().” This method has a special meaning for Code Igniter, since it will be called automatically whenever it finds it was implemented by a specific controller.

Still with me? Great! Then, it’s time to analyze what this method actually does. As you can see, it defines the data that will be passed in to the view file to be displayed later on. This data is first stored on a simple $data array, and second transferred to a view template, called “helloworld.php.”

Each time a view file needs to be loaded, Code Igniter uses a “Loader” class, which is included by default by each new controller created. So, in this case the below expression:

$this->load->view(‘helloworld’,$data);

simply loads the corresponding view file and passes the data that will be printed on the browser to it. Pretty intuitive, right?

Now that you’ve hopefully grasped how the previous “HelloWorld” controller class works, I’m sure that you’ll want to see how the respective “helloworld.php” view file looks. Below I included the definition of the file in question, which should be saved to the /system/application/views/ folder:

<html>

<head>

<title><?php echo $title;?></title>

</head>

<body>

<h1><?php echo $message?></h1>

</body>

</html>

As shown above, the structure of the “helloworld.php” view file is extremely simple. It only contains a couple of “echo” PHP statements, which are used to display the data passed by the controller. Also, you should recall that this data was stored on a $data array, so its respective keys are automatically turned into variables within the view template.

So far, so good. At this point, you hopefully understand how the controller passes certain data in the form of an array to a view file to be echoed to the browser. However, it’s possible that you’re wondering how to test the previous “HelloWorld” controller with Code Igniter.

Code Igniter uses a special routing process that permits you to invoke a specific controller by using an URL. The first URL segment is the name of the controller that will be loaded by a certain application, then the second segment corresponds to the name of a method of the controller that will be invoked. The third segment is an optional argument taken by this method.

This explanation might sound pretty confusing to you. However, the following code sample should dissipate any possible doubts you might have. To call the previous “HelloWord” controller, I’d type the following URL:

http://localhost/codeigniter/index.php/helloworld/

As you can see, the first URL segment calls the “HelloWorld” controller, and automatically executes its “index()” method, which displays the view file previously created. Try it for yourself and you’ll see the classic “Hello World” message printed on your screen.

In addition, to clarify how Code Igniter’s routing process works, say that I changed the definition of the “HelloWorld” controller class and now it looks like this:

class HelloWorld extends Controller{

function HelloWorld(){

// load controller parent

parent::Controller();

}

function display(){

$data[‘title’]=’My first application created with Code Igniter’;

$data[‘message’]=’Hello world!’;

// load ‘helloworld’ view

$this->load->view(‘helloworld’,$data);

}

}

In this case, the URL that should be used to call the “display()” method of the controller would be:

http://localhost/codeigniter/index.php/helloworld/display/

Pretty easy to grasp, right? By using this routing method, Code Igniter assures that all of the URLs generated by a PHP application will look clear and be search engine-friendly as well.

And with this final hands-on example, I’m finishing this first tutorial of this series. As you saw before, I provided you with concrete material that hopefully will help you start mastering the basic features of Code Igniter. You have a lot of fun ahead!

Final thoughts

In this first chapter of the series, I walked you through the core concepts that surround the use of the Code Igniter PHP framework. You hopefully learned how to correctly setup its configuration files, and how to create a simple web application comprised of a single controller and a view file.

I’m only scratching the surface when it comes to discussing the vast set of handy features that come bundled with Code Igniter. Therefore, in the next article, I’ll be covering the use of models and the utilization of some of its core classes.