Introduction to Code Igniter: Part 1

18 comments | Posted: 20 May 06 in Tutorials, by Yannick Lyn Fatt

Please note the following tutorial was done using an older version of CodeIgniter. As such, somethings may not work properly in more recent versions of the framework. Please visit the CodeIgniter website and download version 1.3.3 or 1.4.1, if you would like to run this tutorial in it’s original form. For Updated code please download intro-to-codeigniter-code.zip


What is Code Igniter?

With all the buzz lately being about Ruby on Rails and more recently Django, there has been a little fire burning in the PHP camp and I’m not talking about an argument or any hatred towards Rails or Django. Oh no, I am speaking about a new PHP framework called Code Igniter. What is Code Igniter you ask?

Code Igniter is an Open Source Web Application Framework
that makes writing kick-ass PHP programs simple as apple pie.

It is developed by the fine people over at pMachine, creators of the Expression Engine CMS. Code Igniter (CI) uses the Model-View-Controller (MVC) approach similar to that of Ruby on Rails. However, it is a bit loose in it’s approach to MVC as a model does not have to be used. CI is lightweight, which means it starts you off with just the basic libraries and you can load more if needed. Speaking of libraries, CI comes with a nice selection of libraries to get you going quickly, such as connecting to a database, sending email, validating form data, maintaining sessions, manipulating images, and more. Another thing to keep in mind is that CI’s user guide is superb and the forums are alive with people who are more than willing to help. Both will prove to be invaluable when starting out!

Let’s get Started

Now that you know what CI is, lets take a little look at it’s structure. First of all you will need to download CI. Unlike RoR you don’t need to install anything, as long as you have a webserver with php and mysql you are pretty much good to go. There is also no need to type anything at the command line, which some might be a little more comfortable with.

Now that you have the files drop them into a folder on your webserver. I will call mine regform since I will be showing you how to do a simple registration form for some seminars that sends an e-mail to the organizers and also saves to a database on submission. You will notice that you have a folder called system. This contains everything you will need to use CI. In the system folder there are other folders, but we will only concern ourself with the application folder, since that is where all our views, controllers and models are kept.

Within that application folder you have:

Ok now I know you are itching to get to the coding aspect, but please bear with me as we get a few things setup that will help us later. Open the config folder and then open config.php. At about line 14 you should see:

$config['base_url']	= "http://www.your-site.com/";

Edit this replacing http://www.your-site.com/ with your URL. In my case, since I am working on this tutorial locally, mine will look like this:

$config['base_url']	= "http://localhost/regform";

Now save that file and open autoload.php. On line 42, let’s add the e-mail core class:

$autoload['core'] = array('email');

and on line 54 let’s add the form and url helpers.

$autoload['helper'] = array('url', 'form');

and you can save that file. The reason for adding the e-mail core class is pretty obvious since one of the features of our registration form is to notify the organizers when someone has submitted a completed form. The reason for adding the url and form helpers, however, might not be so clear. You may be thinking to yourself, “Hey I can code this normally using HTML and PHP.” Sure you can, but by adding these that process can be done quicker.

Controllers

With those core classes and helpers now loaded, let us create our first controller. Create a new php file called form.php with the following code and save it to your controllers folder.

<?php
class Form extends Controller {
     function index()
     {
          echo "Jesus Rocks!";
     }
}
?>

Now go to http://localhost/regform/index.php/form or whatever your base URL is with “/index.php/form” after it. You should see “Jesus Rocks!” printed on your screen. Cool huh? Okay, maybe it’s not that cool, so lets take it a bit further by adding something more dynamic and also creating a view. But before we do that, I’m sure you’re wondering why we have “index.php” in our URL. Surely that can’t be a “clean” URL. While it’s not the cleanest, that is the default way CI handles URL’s, however, the index.php can be removed by using adding some rules to an .htaccess file. For the sake of this tutorial though we won’t be doing that.

We can now remove the echo statement from the index function in our controller and instead replace it with the following:

<?php
class Form extends Controller {
  function index()
  {
    #Input and textarea field attributes
    $data['fname'] = array('name' => 'fname', 'id' => 'fname');
    $data['email'] = array('name' => 'email', 'id' => 'email');
    $data['comments'] = array('name' => 'comments', 'id' => 'comments');

    #Checkbox attributes
    $data['purpose'] = array('name' => 'seminar', 'id' => 'purpose');
    $data['prepare'] = array('name' => 'seminar', 'id' => 'prepare');
    $data['principles'] = array('name' => 'seminar', 'id' => 'principles');
    $data['power'] = array('name' => 'seminar', 'id' => 'power');

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

Essentially what we are doing here is creating an array of variables which themselves contain an array of data which we will use in our view. The values in our $data array’s represent our variables and the attribute and value pairs in the respective arrays will be used to construct our form elements as we will see next. Also the last line of our function deals with loading our view and importing our data array so that we can use our variables.

Views

Create a new file called form_view.php and save it in the views folder. Enter the following HTML code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Godbit Code Igniter Tutorial: Creating a simple Registration Form</title>
<style type="text/css">
body {
	font: small/1.5em Verdana, Arial, Helvetica, serif;
}
</style>
</head>
<body>
  <h1>Registration Form</h1>
  <p>Please complete the following form:</p>
  <?php echo form_open('form/submit'); ?>
  <p><label for="fname">Full Name: </label><br /><?php echo form_input($fname); ?></p>
  <p><label for="email">E-mail: </label><br /><?php echo form_input($email); ?></p>
  <p>Please select one or more seminars, that you would like to attend</p>
  <p><?php echo form_checkbox($purpose); ?> <label for="purpose">Purpose of Prayer</label></p>
  <p><?php echo form_checkbox($prepare); ?> <label for="prepare">Prepare for Prayer</label></p>
  <p><?php echo form_checkbox($principles); ?> <label for="principles">Principles of Prayer</label></p>
  <p><?php echo form_checkbox($power); ?> <label for="power">Power in Prayer</label></p>
  <p><label for="comments">Comments: </label><br /><?php echo form_textarea($comments); ?></p>
  <?php echo form_submit('submit', 'Submit'); ?>
  <?php echo form_close(); ?>
</body>
</html>

Looking at the code, you will notice that we have some snippets of php code that represent our form elements. Those are CI’s functions and they became available to us when we loaded the form helper in our config.php file. $form_open(‘form/submit’) creates your opening form element and the form/submit represents the action attribute that you would normally use in a <form> tag, with form being our controller and submit being our function that deals with submitting our form(which we will create in Part 2). form_input($fname) creates an input field for our form with the attributes and values that we specified in our $data['fname'] array in our controller. As for form_checkbox($purpose), that is pretty similar to the form_input() function except it creates a checkbox instead. With form_submit('submit', 'Submit') a submit button is created with type attribute “submit” and value attribute “Submit”. And form_close() simply represents </form>. I know..I know it probably is simpler to just use the </form> as opposed to the PHP equivalent, but you can decide which you prefer.

Ok, now that we’ve finished our form, lets see what it looks like. Open up http://localhost/regform/index.php/form and you should see your form. It doesn’t look pretty but it’s certainly a start.

Conclusion

I hope you enjoyed Part 1 of this series introducing you to the PHP framework Code Igniter. This was just a peek into CI and some of it’s functionality, in Part 2 we’ll take a look at making the form send an e-mail to the organizers and adding the registrant to a database. Until Part 2 comes out feel free to take a look at the the introductory videos on the CI website and also have a read through the User Guide to learn more.

The code for this tutorial is also available for download: regform.zip

Discuss This Topic

  1. 1 Robert

    Nice write-up Yannick!

     
  2. 2 peter heart

    everybody interested in code igniter has to step into the forum mentioned above. this new framework needs publicity.

     
  3. 3 Scott

    We’ve adopted CodeIgniter here at the office as our framework of choice. Before that, we just coded straight PHP. We’ve estimated a 30-50% decrease in production time since using CI. It’s great stuff and I think everyone should give it a try.

     
  4. 4 Yannick

    Robert: Thanks! :)

    Peter: Yup it definitely needs a bit more publicity. It’s a good framework.

    Scott: That’s pretty good. Nice to see figures like that backing up CI.

     
  5. 5 Nathan Logan

    Yannick, great stuff – thanks a lot for putting this tutorial together.

    I’ve also heard great things about CakePHP, which is where I think I’ll head when I get some time to dive into a framework. But who knows – I may come running back to Code Igniter.

    Thanks again for the great run-through!

     
  6. 6 Yannick

    No problem Nathan L. There is still Part 2 to come and maybe a Part 3 depending on how much I can put into Part 2. As I use it more and more maybe I’ll do some more.

    I’d say give CI another try but if you do go to CakePHP then I’d love to hear what you have to say about it.

     
  7. 7 Lisa

    Great Write up, Yannick!

    I didn’t know this existed—and my head is still buzzing with excitement. I’ve been hacking php a bit and it will be nice to put some structure
    into my work!

    Thanks

    Lisa

     
  8. 8 Scott

    We tested CakePHP, but at the time it was still in beta. One of our programmers helped work on the project early on, but said he dropped out due to poor coding standards and a general lack of primary focus for the project. I’ve looked at it now that it’s gone to 1.0 and it seems to be a much larger footprint than CI.

     
  9. 9 Yannick

    Lisa: Thanks, I’m glad you liked the write up. I know once you start using it, you’ll be buzzing even more.

    Blessings.

    Scott: Thanks for giving a little info on CakePHP. I’m sure it has it’s advantages also, but yeah it is a much larger footprint that CI from what I have heard also.

     
  10. 10 ben

    Nice tutorial. I look forward to the rest of the series. I do have one question, though. Isn’t the base url supposed to end with a trailing slash?

    For example, instead of:
    $config[‘base_url’]= “http://localhost/regform”;

    It should be:
    $config[‘base_url’]= “http://localhost/regform/”;

     
  11. 11 Yannick

    Hi Ben,

    I don’t think you have to put the trailing slash. I tried it with and without it and everything seemed to work fine. Did you encounter a problem?

     
  12. 12 SANJEEV

    This is a pretty neat introductory article Yannick, and I am sure the forthcoming tutorials will be as simple to understand as this one!!

     
  13. 13 Yannick

    Thank you Sanjeev. Good to hear that you found it simple to understand. I do hope to do the others in a similar fashion.

     
  14. 14 Eric

    I get page cannot be found in IE and No input file specified in Firefox.

     
  15. 15 Yannick

    Eric:

    What were you doing when you got that error?

    Have you tried downloading the code that I used and checked to see if it’s similar to what you have?

     
  16. 16 David Hemphill

    Awesome, tutorial. I hope this framework gets some more buzz going for it.

    I’ve been playing around with CI too and I love it, but I think it’s worth mentioning that you can use PHP’s alternate syntax for the form helpers.

     
  17. 17 Tim

    Nice article! I have build a platform for open source graphic design at http://www.commonsdesign.com using CI. It`s pleasure to work with i must say.

     
  18. 18 Yannick

    David: Yeah I could have used the alternate syntax but in the environment I work it causes problems with the XML declaration, so I figure to keep things safe and simple (and even more so some people are not able to edit their php.ini file), I might as well do it the long way. Maybe I can mention it in the next article.

    Tim: That’s pretty good man. I like the site.

     

Comments closed after 2 weeks.