Get started with CodeIgniter

Get started with CodeIgniter

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on January 20, 2010

I’ve never really got the hang of PHP frameworks and have tended to use my own custom built CMS but even with this I still find myself writing the same code over and over again. In the past I’ve dabbled with CakePHP and the Zend Framework and not really got very far, so a few days ago I downloaded CodeIgniter. Although I’m extremely new to this I was pretty blown away by the simplicity of setting things up and getting an actual webpage that processes something online.

How It Works

CodeIgniter uses the MVC or Model View Controller architectural pattern, if your not familiar with MVC it is a logical object orientated development approach. below we look at a simple example of how we use the MVC.

mvc

Controllers

A controller is simply a class file that is named in a way that can be associated with a URI. For example if i have a controller with the filename account.php the URI to reach that page would be something like http://your-domain.com/account/ so you no longer need to fiddle with the .htaccess file and mod_rewrite to enable SEO friendly URI’s. The controller is the top level file for each page that allows you to include database requests in the form of ‘Models’ and templates as ‘Views’. below is an example of a controller, This code would be saved in the file blog.php, it’s important to understand the naming convensions because the name of the file is always the name of the class with the first letter capitalised. Within the Blog class we have an index() function which is always loaded when the page is excecuted. For example if we had another function lets say ‘categories’ the code within that function would only be executed if we visited http://your-domain.com/blog/categories/ this is also the way you can pass url parameters into functions but we’ll leave that for another day. We’re loading our ‘View’ in at the bottom and passing the array $data into it. Within the view file which would be called blogview.php if we wanted to echo the heading we’d simply echo $heading the same with the title. With the to do list we would need to setup a for each loop to cycle through the results in that array.


class Blog extends Controller {

	function index()
	{
		$data['todo_list'] = array('Clean House', 'Call Mom', 'Run Errands');
		$data['title'] = 'My Real Title';
		$data['heading'] = 'My Real Heading';

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

Models

As yet we’re not using a model, this is because our controller isn’t doing anything complex. If we wanted to connect to a database and get a set of results we would use a model which could look like the below. This is all the code we need to pull 10 results from the database which would be returned to the controller in an array. note that you would need to replace ‘tableName’ with your own database table name.

class Blogmodel extends Model {

    function Blogmodel()
    {
        // Call the Model constructor
        parent::Model();
    }

    function get_last_ten_entries()
    {
        $query = $this->db->get('tableName', 10);
        return $query->result();
    }

}

To include the model firstly you need to navigate to system/application/config/database.php and add your database connection details. then below you’ll see that i’ve modified the controller that we used earlier so it now connects to the database and gets our data. This will then be sent through to the ‘view’.


class Blog extends Controller {

	function index()
	{

		$data['title'] = 'My Blog Site';
		$data['heading'] = '10 of my blogs';

                 // connect to DB and get data
                $this->load->database();
                $this->load->model('blogmodel');
		$data['query'] = $this->blogmodel->get_last_ten_entries();

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

Views

Simply put a ‘View’ is our template, it’s where our data gets rendered and is made pretty, you can have as many views as you like and pass whatever data you like into them it’s probably a good idea to have a header, main content area and footer, but for the purposes of this demo i’ve used one view where all the data is rendered.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title><?php echo $title;?></title>
</head>

<body>

<h1><?php echo $heading;?></h1>

<?php foreach($query as $item):?>

<h2><?php echo $item->title;?></h2>
<?php echo $item->content;?>

<?php endforeach;?>
</body>
</html>

For more information on where you can find the download and user guide Click Here.

More tutorials from Papermashup
Comments
7 discussions around Get started with CodeIgniter
  1. anis ur rehman says:

    thx. i am new user of this and this intro is realy helped me to go further

  2. Pingback: Getting Started with CodeIgniter and How to Create All Those Great Apps « Web Development News

  3. Daniel says:

    I have used both CI and CakePHP. After developing for a long time and for a living. You can develop much more robust applications much faster using CakePHP. It does have a steeper learning curve than CI, but the Convention over Configuration paradigm is key. CakePHP promotes code reuse a lot more than CI. I find myself writing much less code using CakePHP. The ORM is also awesome compared to CI’s Active Record implementation. Cake also has a Auth component and an Access Control List component witch CI is lacking. If you are new to PHP frameworks CI is the way to go. Once you are comfortable in a framework like CI you will find that it is lacking compared to CakePHP.

  4. Jeff says:

    Nice overview, thanks! I know that I have a friend that is big into PHP framework usage and he used to use CI but has since migrated to Kohana (http://kohanaphp.com/), saying that while based on CI, it is MUCH better and even faster.

    Thanks again!

    Jeff

  5. Pingback: uberVU - social comments

  6. Martin says:

    Nice intro to codeigniter, I’ve been waiting for the right project to try out CI, looks promising.

  7. Pingback: abcphp.com

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Looking for a registry cleaner to speed up your PC and show a full diagnostics?
Faster surfing with Dish Network High Speed Internet

Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in touch.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com you can find details here Or use the contact link below for further advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.