Rapid Application Development with CodeIgniterby: Akash MehtaWhy should you be using CodeIgniter?
There's a lot of choice for PHP frameworks out there. A quick look at this list
reveals quite a few options, each with advantages and disadvantages.
Many frameworks offer ORM, or Object-relational Mapping; some offer
authentication systems or AJAX interfaces inbuilt. Chances are,
however, that you just want to get on with coding, and don't want to
have to deal with complex libraries. CodeIgniter achieves this
wonderfully, staying out of your way but offering a lot of
functionality if and when you need it.MVC 101 In a framework-less PHP application, you'll typically have a number of seperate PHP scripts, each of which is accessed directly by the client. There might be a global header and footer, possibly with some standard functionality for database access. There are a number of problems with this approach, however, including inconsistent application entry points, repetition of code for standard tasks and so on. As the application grows, it can also become very inconsistent and hard to maintain. The MVC design pattern goes a long way towards solving this. In MVC, your application is split into three parts - the Model, the View and the Controller. The Controller controls application flow and routing, handing off requests to other parts of the application. The Model manages data related to your application. Finally, the View represents the interface to your application, in this case our HTML front-ends. Views can contain basic logic, but most complex routines lie in the model. The one problem with MVC, however, is that all this clean seperation is only effective if you observe it. You should start with the basic purpose of each section. For example, never access the database in your controller or view - that's what the model is for. Never output HTML in your controller or model, leave it to the view; and certainly never handle redirects within your view. Still, here's what you should do. Your views can (and probably should) contain basic loops and simple Introducing CodeIgniter! Before we delve into the internals of CodeIgniter, let's have a look at a quick sample of how it works. Grab a copy of CodeIgniter from CodeIgniter; I'll be working with version 1.6.1 in this example. Let's say we have a very basic application that takes a name via the URL and writes out, "Hello $name!". Here's how we would build it in just PHP, and then in PHP with CodeIgniter. Raw PHPindex.php:<?php Not exactly the best PHP script ever, but it should do for our demonstration. CodeIgniterCodeIgniter enforces consistent and effective file seperation from the ground up, with a simple filesystem structure as part of their implementation of MVC. The system/application folder has subfolders called 'controllers', 'models' and 'views'. system/application/controllers/hello.php<?phpsystem/application/views/show_name.php Here you can see we have two seperate files, which, as you might
have guessed, are the controller and view. The controller is entirely
OOP; the Notice that the view looks much cleaner than the echo calls we used earlier. Sure, you could jump in and out of PHP for that small example; maybe you only need one line of code to achieve the same functionality. Now, if your application is that simple and you aren't worried about XSS vulnerabilities, it's okay. However, our CodeIgniter version is better prepared to increase in complexity, with clean seperation between the business logic and the presentation. When we extend this in future, we can easily modify the frontend or the backend (or both) while making it easy to keep track of everything. Anyway, in this example, our controller class Hello is extending the
CodeIgniter class Controller giving it access to the framework core.
This includes functionality for input filtering, the library for which
is loaded at If I point my browser to Just a note on URLs: when you drop CodeIgniter into your website, it
takes over as the application entry point (from its root installation
directory, e.g. Notice the framework also handles clean search-engine-friendly URLs for us. Oh, and the glaring XSS vulnerability in our pure-PHP example earlier? Try putting anything vaguely harmful into the URL and CodeIgniter will reject it. It's XSS-proof already, with not a single input validation routine in sight. We've barely started and already CodeIgniter is making our life easier. 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 ' Setting up CodeIgniterYou'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 Open up 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"; CodeIgniter helps you quickly move code between servers with different database configuration details. The Planning our applicationWe'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 controllerAs 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 system/application/controllers/jobs.php<?php 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 is CodeIgniter's approach to models - The modelWe haven't actually covered a model yet. Similar to controllers, they extend the As you saw in our controller, our model will have two methods, one to fetch all jobs in the database - 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 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
Notice we're using PHP5's method chaining - calling the Our 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` ( 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 viewThis 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 basically tells CodeIgniter to load up the view at Array Now, maybe you could have got to this stage quicker with simple system/application/views/jobs_view.php<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> 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:
Further CodeIgniter If you enjoyed this tutorial and you're interested in CodeIgniter, you should definitely take 15 minutes to run through the video tutorials on the official website. The blog tutorial is an excellent demonstration of what CodeIgniter can do in practice, making use of the various features of the framework; in this tutorial, we've only really touched upon the basics of the MVC implementation. The wiki is also an excellent destination for further reading - this page has a good list of topics you can choose from - although the content there can be a little complex and is not designed for the novice user (yet!). © 2008 NetVisits, Inc. All rights reserved. |