Codular

HomeWriters RSS

Introduction to CodeIgniter

Introduction

After building a few web applications you will find that you spend a considerable amount of time writing the same thing, user authentication, templating, database models and caching. This is where a framework comes in very useful because frameworks provide a starting block for you to work with.

CodeIgniter

We will be using CodeIgniter which is described as "a powerful PHP framework with a very small footprint"

For this tutorial you will require:

First Download CodeIgniter 2.1, then extract the files and place them in a web root, your structure should look like:

document_root/
    application/
    system/
    index.php

Then open up the website in a browser, you should see a "Welcome to CodeIgniter" page, if so that's great, we're ready to get started.

Model-View-Controller (MVC)

The Model-View-Controller design pattern separates application logic from presentation. The components are:

Controllers

We are going to create a news controller, to do this create a file called news.php within the document_root/application/controllers/ folder.

Within this file we will define a class; the class will be called News (notice the uppercase of the first word. If our filename was newsandevents.php the class name would be Newsandevents.)

Within this class we will create an index method, and this method will echo a string.

Our news controller is shown below:

class News extends CI_Controller {

    /**
     * News home page, found at /news
     */
    public function index()
    {
        echo 'News home page';
    }

}

Now if you navigate to /index.php/news you should see what we echoed out in our index method.

The index name is special and will be routed to the 'base' of news; if we had named our method list then we would access this at /index.php/news/list

Pretty URLs

At this point you might be wondering why you have to have index.php in your URLs - they don't look pretty and we want to remove them. Pretty much all frameworks have what is known as an entry page in our case this is index.php - this page will take a string and decide which controller should be run.

Removing it

To remove this we'll be using a htaccess file (if your using a web server other than Apache2 I'll make the assumption you know how to do this.) ensure htaccess is enabled, if you're not sure how to do this, use Google.

What the htaccess file does (behind the scenes) is add index.php back into the URLs.

Create a .htaccess file in the root of your application, and paste in the following rules:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # Removes access to the system folder by users.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    # Removes access to the application folder by users.
    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    # Checks to see if the user is attempting to access a valid file, such as an image or css document, if this isn't true it sends the request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's can be sent to index.php, and everything works as normal.
    ErrorDocument 404 /index.php
</IfModule>

Now open up the document_root/application/config/config.php file and you should see a line $config['index_page'] = 'index.php'; change this to:

$config['index_page'] = '';

If everything is working, you should now be able to access the index method of our news controller at /news

Views

Your views are where your HTML should live. To start off we'll create a new file called news-list.php within the document_root/application/views/ folder, and within this file enter some arbitrary text - it doesn't matter what you put, this is just for demonstrative purposes.

Loading a View

Now go back to your news controller (the news.php file within the application/controllers/ folder.)

We are going to replace our echo statement with:

$this->load->view('news-list');

Now if we load the /news page you should see the text you entered into the news-list.php file.

Organising Your Views Folder

We can organise our views folder which makes managing large application easier, for example if we had created our news list view at document_root/application/views/news/list.php we would call this with $this->load->view('news/list');

Routing

We will now make the news list page run as the homepage.

Default Welcome Page

You will have noticed that within the document_root/application/controllers/ and document_root/application/views/ folders there were welcome files welcome.php and welcome_message.php respectively.

When you go to the root of your website this controller (which calls the view) is run.

We don't require these files anymore, so we'll delete these.

Set the Default Controller

Open up the document_root/application/config/routes.php file and you should see a line $route['default_controller'] = "welcome";

The default controller is what will be loaded for the root of the website; we want to change this to:

$route['default_controller'] = 'news';

Set a Custom Route

We can route anything to any controller, and we can also route to specific method within a controller, for example:

$route['codeigniter-rocks'] = 'news/something_random';

The above route would allow us to load the something_random method within the news controller when we call /codeigniter-rocks

Passing Data to a View

You will rarely, if ever, build a web application that doesn't involve display some dynamic data on the front end, because we are using the MVC design pattern, this means our data should be managed in the model, read by the controller and the HTML generated in the view.

This means we have to pass the data from the controller to the view, you will remember we loaded our view using $this->load->view('news-list');

In CodeIgniter we can easily pass an associative array (or an object) of data into a view, for instance:

$data['first_name'] = 'Joel';

You can then load the data in the view by referencing the array keys as a variable, so in the example above you could call <?php echo $first_name; ?>

In our demo we will define a news item, open up the document_root/application/controllers/news.php and make the updates shown below:

// Define the news items
$data = array(
    'news' => array(
        array(
            'id' => 1,
            'title' => 'Demo Title',
            'copy' => 'Some random copy'
        )
    )
);

// Load the news list view
$this->load->view('news-list', $data);

Then open up your view, document_root/application/views/news-list.php and add the following code:

<?php foreach ($news as $news_item) : ?>
    <h3><?php echo $news_item['title']; ?></h3>
    <?php echo $news_item['copy']; ?>
<?php endforeach; ?>

When you load /news you should see the dynamic data.

Models

We are going to create a model with a method to read news items from table in a database (for this demo you will have to populate the table manually.)

The SQL to create the table is:

CREATE TABLE `news` (
    `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
    `title` varchar(255) NOT NULL,
    `copy` text NOT NULL,
    PRIMARY KEY (`id`)
);

Connecting to a Database

To connect to this table we'll be using CodeIgniters database methods, we must first set some database settings within document_root/application/config/database.php the file will have the following lines:

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = '';
$db['default']['password'] = '';
$db['default']['database'] = '';

Populate these with the correct details (you can get these from your hosting provider if you don't know them.)

You will then need to load the database, most applications will require the database on most page loads, so what we're going to do it autoload the database library, this means that the database will always be loaded (without explicitly having to call it) to do that, edit the document_root/application/config/autoload.php file and find the line $autoload['libraries'] = array(); add the an item called database as shown below:

$autoload['libraries'] = array('database');

Creating a Model

We are going to create a new file called news_m.php within the document_root/application/models/ folder.

Our model is made of a class, which will be called News_m and will extent the default CodeIgniter model.

We will define a table at the top of the class; we then don't have to hard code the table name within the methods.

We will set a read method which will return an associative array of all news items found in the database.

The code for this is shown below:

class News_m extends CI_Model {

    /**
     * Define the table name
     */
    private $_table = 'news';

    /**
     * Read all news items
     */
    public function read()
    {

        // Return an associative array of all news items
        return $this->db
            ->get($this->_table)
            ->result_array();

    }

}

Loading a Model

As with the database library the model has to be loaded before we can use it, we could autoload the model as we did width the database; however it is unlikely that our whole application will require the news model, so we will load it only when required in the controller.

We are going to load our news model at the top of our index method (in the news controller) as shown in the code below:

public function index()
{

    // Load required models
    $this->load->model('news_m');
}

Calling Methods of a Model

Once we've loaded our model we can call it using the code below:

// Read the latest news posts
$data['news'] = $this->news_m->read();

Add the above code to your news controller and it should look like this:

public function index()
{

    // Load required models
    $this->load->model('news_m');

    // Read the latest news posts
    $data['news'] = $this->news_m->read();

    // Load the news list view
    $this->load->view('news-list', $data);

}

If you take a look at the /news page (so long as you have added some data to your newly added news table) you should see some articles being pulled in dynamically.

Libraries

We have already used the built in database library, there are many other built in libraries which you may find useful, for example form validation and image manipulation.

Conclusion

And that right there is the basic set up of the MVC system, as well as introducing custom routes and dynamic data. The next step of progression would be to work with user supplied data, so in our example above we might build a form which allows admins to create new news stories, or allow users to post comments etc.

Tags: PHP, Frameworks