Helping ordinary people create extraordinary websites!

Rapid Application Development with CodeIgniter

By Akash Mehta
2008-02-17

Getting our feet wet

As an example to introduce you to CodeIgniter, we're going to build a simple job board. Jobs will be pre-populated in a database table called 'jobs'. There will be two pages - a list of available jobs, and a detailed summary page for each job. So, without further ado, let's get into it!

Setting up CodeIgniter

You'll need an Apache-powered PHP+MySQL server for these examples. First, download CodeIgniter. Extract it into your web directory under a subfolder; I recommend /ci to help following along, but it doesn't really matter. We won't tackle environment tweaks, but rather demonstrate the power of CodeIgniter and how you can use it.

Open up system/application/config.php in your CodeIgniter folder. It's pretty self explanatory, and is wonderfully commented too. You'll need to set $config['base_url'], and, well, that's about it. Fire up your web browser and point it at the location of your CI installation and you should see a welcome page with a few basic instructions.

We'll also have to configure database access. open up system/application/database.php and scroll to the bottom. You probably only need to edit these entries:

system/application/config/database.php
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "";
$db['default']['password'] = "";
$db['default']['database'] = "";
...

CodeIgniter helps you quickly move code between servers with different database configuration details. The 'default' here refers to the active configuration group, defined a few lines above in $active_group. This also makes connecting to multiple databases on different servers easy. Check out the manual for more details. Make sure the database you specify exists; you may want to use a table name prefix if you want/need to use an existing database, in which case set $db['default']['dbprefix'] to something like citest_.

Planning our application

We're going to keep it simple here. Most frameworks like to demonstrate with a blog system; we won't even go that far, but once you've finished reading through this, CodeIgniter has quite a nice collection of video tutorials. For our job board, we'll have one controller, one model and two views. The controller will handle both the main job list and the job summary pages, with a model method and view for each. In this way, we'll clearly seperate the different parts of our application.

Just a note on CodeIgniter naming conventions: all file names are lower case, all class names start with an uppercase letter and are in files of the same name (plus the .php extension). CodeIgniter does alter the capitalization of names you pass to it, so under_scores are used as opposed to StudlyCaps or camelCase.

The controller

As we briefly covered before, a controller is basically a class with a few methods that handles incoming requests and directs them accordingly. The class extends CodeIgniter's Controller class, and in doing so gains access to all the functionality of the framework. In our controller, we'll load the various resources we're going to need - specifically, a model and some views. None of this, especially the model, is loaded by default - CodeIgniter is designed to run very lightweight. The object at $this->load provides a system for loading such resources, as we'll see in a moment. Here's the code for the controller:

system/application/controllers/jobs.php
<?php
class Jobs extends Controller {
function index() {
// This gives us redirect()
$this->load->helper('url');
redirect('jobs/list_jobs');
}

function list_jobs() {
$this->load->database();
$this->load->model('jobs_model');
$data['jobs'] = $this->jobs_model->get_jobs();

// This gives us anchor() - see the view at the end
$this->load->helper('url');
$this->load->view('jobs_view', $data);
}

function view_job($id = false) {
$this->load->helper('url');
if (!$id) redirect('jobs/list_jobs');

$this->load->database();
$this->load->model('jobs_model');
$data['job'] = $this->jobs_model->get_job($id);

$this->load->view('job_view', $data);
}
}

As you can see, the controller is fairly simple, merely taking input, fetching data from the model and sending it to the view. We start the bulk of each routine with $this->load->database(), which will connect to the database and prepare the database interface library for us using the settings we defined earlier. Then we initialise our model.

This is CodeIgniter's approach to models - $this->load->model('classname') will load up the file at system/application/models/classname.php and initialise an instance of the class Classname within the file (you shouldn't really include other files). It will then put a reference to the new object at $this->classname. You can override this particular behaviour by passing a second argument, a string, to be used as the property name for the object. For example, you could call $this->load->model('someclass', 'data'); and access the model class at $this->data instead of $this->someclass . So, now that we're already making use of our wonderfully non-existent models and views, let's actually create them!

The model

We haven't actually covered a model yet. Similar to controllers, they extend the Model class. Once the database is initialised, through a call to $this->load->database(), they have access to the extensive database class of CodeIgniter.

As you saw in our controller, our model will have two methods, one to fetch all jobs in the database - get_jobs() - and one to fetch details for a particular job - get_job($job_id). There is no particular naming convention for models, however I typically use the controller name with a _model on the end. It's either this or you pick a different name entirely - CodeIgniter isn't magical, and it can't help you load two classes with the same name.

The CodeIgniter manual has an excellent quick start guide for the database library that you should read through before proceeding. Here's the code for our model:

system/application/models/jobs_model.php
<?php
class Jobs_model extends Model {
function get_jobs() {
$query = $this->db->get('jobs');
foreach ($query->result_array() as $row)
{
$result[] = $row;
}
return $result;
}

function get_job($job_id) {
$query = $this->db->where('id', $job_id)->get('jobs');
$result = $query->row_array();
return $result;
}
}

Let's take a moment to examine this, as it's probably the most complicated section of the tutorial. CodeIgniter has an (optional) Active Record class that allows developers to access their databases in an Active Record-style manner. You can write your own raw SQL queries and pass them to $this->db->query(), but there are a number of advantages to using the Active Record class, not the least of which is CodeIgniter will handle your table prefixes for you. Take a sample SELECT * FROM table WHERE id='0' query. Using the Active Record class, you would write it like this:

$this->db->select('*')
->from('table')
->where('id', '0')
->get();

Notice we're using PHP5's method chaining - calling the select() method, then the from() method, and finally the where() method. Each of these methods returns $this in their own context - i.e. when you call them you get back what you called them from; in this case, $this->db.

Our get() method is important, as it's the one method (besides getwhere(), which we won't cover here) that ends the query. When called, it tells the database library to construct the SQL query based on the information passed in already (where information is missing, it makes assumptions, all the way to a standard SELECT * FROM 'table', where supplying 'table' is compulsory). It then runs the query against the database and returns a query result object. We can manipulate this object easily, such as fetching a row array using the result_array() method. The row_array() method is similar except it will only ever give us a single result row.

So, with that taken care of, we have succesfully fetched data from our database. But wait! We don't yet have a database table! Run this query against your database, substituting table name as appropriate:

CREATE TABLE `jobs` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`title` TEXT NOT NULL,
`company` TEXT NOT NULL,
`description` TEXT NOT NULL
);

This will create a very basic table to store our job data in. Populate it with some sample rows - be creative and come up with some job postings you'd like to see. The table structure isn't meant to be at all representative, and a live job database would have far more data for each job record, however as we don't need any more data to demonstrate CodeIgniter we'll stick with this. Finally, we now have a database layer and some actual data to send through it! Now, on to the view!

The view

This is the final stretch - the presentation of your application. We've taken all the data we need from the database, and we've passed it to our views to be ready. These views won't be pretty - in fact, they may not even be HTML valid - but they're just to demonstrate the basics of MVC in CodeIgniter, so please bear with me here. Let's start with the standard job view.

Now, our view is going to be called jobs_view. We decided this when we coded this line of our controller:

$this->load->view('jobs_view', $data);

This basically tells CodeIgniter to load up the view at system/application/views/jobs_view.php, and to take the associative array $data and create a variable available within the view for each element, e.g. $data['jobs'] would give us a $jobs variable - and that's exactly what happens. Let's print_r($jobs) to see what we're working with first. Create this jobs_view.php file and put a <?=print_r($jobs)?> in it. You should see something like the following:

Array
(
[0] => Array
(
[id] => 1
[title] => Web Developer
[company] => Google
[description] => Develop kick-ass web applications
for the mighty Google.
)

[1] => Array
(
[id] => 2
[title] => Sr. Web Developer
[company] => Ellis Lab
[description] => Help the world develop kick-ass web
applications with our software.
)

)

Now, maybe you could have got to this stage quicker with simple mysql_query() and mysql_fetch_array(), but as you extend your application you'll definitely find the framework approach easier and more efficient. In any case, now that we have our array, manipulating is almost self explanatory. We'll use a basic slightly-styled table.

system/application/views/jobs_view.php
<html>
<body>
<table border="1" style="border-collapse: collapse;">
<thead>
<tr>
<th>Job Title</th>
<th>Company</th>
<th>View</th>
</tr>
</thead>
<tbody>
<?php foreach ($jobs as $job): ?>
<tr>
<td><?=$job['title']?></td>
<td><?=$job['company']?></td>
<td><?=anchor('jobs/view_job/'.$job['id'], 'View')?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>

All pretty simple stuff, and very standard PHP. Our final view, for individual jobs, is even easier:

system/application/views/job_view.php
<html>
<head>
<h1>Viewing Job: <?=$job['title']?></h1>
<p><strong><?=$job['company']?></strong></p>
<p><?=$job['description']?></p>
</head>
</html>

And there you have it! A database driven PHP web application built on CodeIgniter. Load up http://localhost/path/to/codeigniter/index.php/jobs/list_jobs and you should see something like this:





Tutorial pages:
 3 Votes

You might also want to check these out:


Leave a Comment on "Rapid Application Development with CodeIgniter"
You must be logged in to post a comment.

Link to This Tutorial Page!


GET OUR NEWSLETTERS