CodeIgniter Tutorial

Introduction

In this CodeIgniter Tutorial, we will introduce you to this framework. You will learn how to install and configure CodeIgniter on Hostinger shared hosting, in addition to building your first ever PHP application utilizing this widely-used framework. You will also find out more about MVC and why it’s critical to modern web development.

What is CodeIgniter

In today’s web development space, efficiency and modularity are all the rage. Gone are the days when you would have to re-write the same code for multiple applications or make a concerted effort on your end to construct your application in a dynamic manner. Modern web frameworks do all of this for you.

CodeIgniter is one of such frameworks available to PHP developers. Arguably the most popular amongst its peers, CodeIgniter greatly accelerates PHP-based web development by virtue of its vast array of libraries and packages. These libraries are designed for such areas of web applications where code reusability is common, thus taking some work off of developers’ plates.

Based on the Model-View-Controller (MCV) architecture, CodeIgniter also adds layering of logic to your web applications. This not only contributes towards a cleaner application design but is also is useful in parallelizing certain processes in the development cycle. As a result, your products are highly responsive to possible business changes and make it to market quicker.

The pre-requisites of this tutorial include basic knowledge of PHP, as well as some experience with Linux command line.

What you’ll need

Step 1 – Installing Codeigniter

To install CodeIgniter, you need to have either Hostinger shared hosting or LAMP (Linux, Apache, MySQL, PHP) already up and running on VPS or your local system. You can follow this tutorial with any distribution of Linux; naturally, we are using Hostinger’s shared hosting account.

First of all, you need to access your account via SSH. If you are not sure how to do this, see this tutorial.

To begin the installation process, open the terminal, and enter the public_html folder. In our case, the following command will do:

cd /public_html

Now, you will need to download the latest distribution of CodeIgniter. You can do this by visiting its official download page, and grabbing the zip file. At the time of writing this tutorial, the latest stable release of CodeIgniter is version 3.1.4.:

wget https://github.com/bcit-ci/CodeIgniter/archive/3.1.4.zip

To unzip the file, run the following command:

unzip 3.1.4.zip

If you are installing CodeIgniter on VPS, it is possible that you don’t have Zip installed on your system. If so, you will be greeted with an error after running the above command. You can simply solve this by downloading and installing unzip, like this:

sudo apt-get install zip

Now you should be able to unzip your copy of CodeIgniter.

Once unzipped, you should be able to see a directory named CodeIgniter-3.1.4 . You can rename this for the convenience if you want to in the following manner:

mv /var/www/CodeIgniter-3.1.4 /var/www/codeigniter

Now, open your browser, and enter the path of this folder:

http://yourdomain.com/codeigniter

You should be able to see CodeIgniter’s default welcome screen. It is your cue now, that the CodeIgniter has been successfully installed on your system.

Step 2 – Configuring Codeigniter

As you have a fresh copy of CodeIgniter, you need to configure it before anything else. While this is the most tedious part of our CodeIgniter tutorial, luckily, the configuration is usually only a one-time headache.

Begin by creating new MySQL database. On Hostinger, you can do this on MySQL databases section.

To start the configuration process, you need to supply CodeIgniter with all the relevant information about your MySQL database. You can do this by altering the database.php file in the CodeIgniter distribution. Open the file by running the following command:

nano /codeigniter/application/config/database.php

The contents of the file should now be visible to you. You need to find the following section of the file and include the information specific to your MySQL database configuration. For example, to connect to a database created on Hostinger, the configuration file should look like this.

Once you have updated the file with all the relevant information, save and close the file. And that’s it – you have successfully synced your database with CodeIgniter.

Moving on further in our CodeIgniter tutorial, you should now set up your domain name. To do this, open the config.php file by doing the following:

nano codeigniter/application/config/config.php

Once opened, find out where the following line is situated, and edit it according to your needs.

$config['base_url'] = 'http://yourdomain.com';

This line means that if you had yourdomain.com as your domain name pointing to the directory where CodeIgniter is installed (last command of Step 1), you will edit the config.php file to look like the above line.

2.1 Configuring Virtual Hosts on VPS

Skip this part if you are installing codeigniter on Hostinger shared hosting.

Virtual Hosts are useful if you want to run multiple application using a single domain name. This can help if you have only a single VPS and multiple applications, productions or otherwise, running on top of it. You can create virtual hosts using your Apache server.

While the creation of virtual hosts is beyond the scope of this tutorial, you need to make some additional changes to CodeIgniter’s configuration before starting formal development.

First off, you need to make sure your document root is synched with the installation directory of CodeIgniter. You can do this by opening the virtual host file:

sudo nano /etc/apache2/sites-enabled/000-default

Once opened, look for the following block and insert the install directory ahead of Document Root:

Finally, you need to let Apache know that it needs to look at the newly created .htaccess file. In order to achieve this, open the virtual hosts file again, and ensure AllowOverride is set to All:

<Directory>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>

Now you won’t be seeing the pesky index.php in your URL. As a result, your URLs will look squeaky clean.

Step 3 – Understanding MVC

To truly understand what makes frameworks like CodeIgniter worth your while, we need to dedicate some of this guide to learning more about MVC.

MVC is predominantly a web development architecture paradigm, which recommends that in any given application, the business logic needs to be decoupled with the presentation. It divides the application into three functional parts: models, views, and controllers.

Models do all the dirty work – they are responsible for dealing with your database, carrying out computations etc. In short, it is where your business logic is located. Views, on the other hand, have nothing to do with the logic of your application. They form the presentation layer of the application, where the data coming from your models is embedded when loading web pages. Controllers are the binding force between models and views. They route user requests to relevant models, and once the model has done its job, they load the relevant view.

As CodeIgniter subscribes to Object-Oriented Programming (OOP), all models and controllers are PHP classes extending the base classes provided by the framework. Views are also PHP files, but in the name only, as the bulk of their content is HTML/CSS. Only snippets of PHP code are present, to display the data provided by the models.

MVC gives developers added flexibility in terms of code reusability and separation of design and development. You can have nested views so that you don’t have to write the same code for multiple views – a good example would be a navigation bar on every webpage of the application. And as both views and models are entirely separate, the front-end developers can work in parallel with the back-end team greatly reducing total development time.

3.1 Routing Basics

In the previous section, we saw how to remove index.php from the format. As a result, this template translates to URLs similar to the following:

http://www.yourdomain.com/welcome/tester/1 Here, welcome is a controller class corresponding to a controller file named welcome.php. Inside this class, it will call the tester() function, and pass ‘1’ as a parameter. Any further parameters can be supplied in a similar fashion, separated by slashes.

As you can see, routing is extremely user-friendly in CodeIgniter. You can play around and create more complex routing, but we won’t be covering it here.

3.2 Libraries

Another important feature of CodeIgniter is – its encouragement of reusing existing solutions to carry out common tasks quickly. CodeIgniter does this by providing libraries and helper functions (helpers). A competitive edge of CodeIgniter is also the fact that developers can pick and choose which libraries to load and when to load them. This results in blazing fast, light-weight yet feature-rich applications, as libraries are loaded on-demand.

Loading a library is very simple in CodeIgniter. For instance, to load the Database library, simply pass the following line in your model or controller (models are recommended, albeit optional in CodeIgniter):

$this->load->database();

Of course, some libraries and helpers are so common that it is, in fact, better to autoload them right at the start of your application boot-up. Examples include the Database library, as databases are an essential part of any modern web application, and the URL helper function which can prove to be useful in loading URLs easily. In order to autoload the Database library, open the following file:

nano application/config/autoload.php

Once opened, replace the line:

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

With this:

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

You can autoload additional libraries in the array() method, separated by commas.

Similarly, for helpers you need to replace this line:

$autoload['helper'] = array();

With this:

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

By getting to know more about MVC, we hope that you can further appreciate the many wonders of CodeIgniter.

Step 4 – Creating Simple App with CodeIgniter

Okay, with the formalities out of the way, we can finally get to the meat of the tutorial. At this point of our CodeIgniter tutorial, you should have a running distribution of CodeIgniter with the changes we made when configuring it in Step 2. You should also be familiar with how models, views, and controllers work in CodeIgniter. In this section, we will use that knowledge to create a simple CodeIgniter web application. The app will be fairly simple in design: we will use our model to fetch movie review grades from our database and show them one-by-one using our view. The controller will be used to route requests between the model and the view. Once you get a grip on these fundamentals of CodeIgniter, you can go ahead and start building rich web applications.

Step 4.1 Pre-Requisites

As stated in the introduction to this tutorial, basic knowledge of MySQL is expected on the reader’s end. For our sample application, we need to create a single table titled reviews with 3 columns named id (primary key and auto-incremented), title and grade.

You should go ahead and create this table, as it will form the basis of our application. CodeIgniter should have access to your database if you followed the instructions in Step 2. After creating the table, fill it with some mock values.

Step 4.2 The Model

After we have our database all sorted out, we can begin working on our business logic. To do this, we will create a model, which will get the values from the database.

Models are placed in the applications/models directory of CodeIgniter. This is done so to prevent making a mess of your application’s directory structure. Go to the directory, and create a new PHP file called reviews_model.php.

nano reviews_model.php

Once created, paste the following code in the file:

<?php
class News_model extends CI_Model {
}
?>

As you can see, your model class News_model extends the generic CI_Model class provided by CodeIgniter. Also note that the first letter of your class is uppercase – CodeIgniter requires all class names to begin with a capital letter.

Now, you need to load the Database library that we talked about in Step 3. This will make working with databases a walk in the park. You can use the constructor method of the model, which will effectively load the library right from the start. To do this, paste the following code inside the class created above:

public function __construct() {
$this->load->database();
}

Now, the database library has become visible to each method within the class. Next up, we need to create another method which will use this database library to query the database:

The above method simply takes in ID as an argument and returns all the information in the columns associated with that ID. So, this method will be called each time we request the review of a movie.

Step 4.3 The Controller

We have taken care of our data retrieval layer. We must now create a route so that when the user requests movie reviews, our yet-uncreated view is supplied with the information we just fetched using the model.

To create a new controller, go to the application/controllers directory, and create a file named reviews.php. Remember: CodeIgniter controllers mandate that the file name is the same as the class defined inside that file. After creating the file, open it, and paste the following code inside:

<?php
class Reviews extends CI_Controller {
}
?>

All we need to do now is to package the data retrieved from our model and pass it on to the view. To do this, we will create a method called show(), which binds this data to a newly created structure and loads the view with that structure passed on to it.

The $data array is an associative array, with keys title and grade corresponding to values received from the database. This array is passed on to the view named movie_review, and the view is subsequently loaded.

Step 4.4 The View

Finally, we have to create a view which will display requested movie reviews.

Enter the application/views folder, and create a new file titled movie_review.php. Note that the name of the file has to correspond to name you told the controller to load (last line of the show() method). After the file’s creation, paste the following code inside:

<?php
print $title;
print $grade;
?>

The view simply displays the title of the movie, as well as its grade just as they were passed to it by the controller in the $data array. Needless to say, the result won’t be very pretty, as we haven’t included any styling to our view. Of course, you can add inline styling (not recommended) or reference a CSS stylesheet in the view.

Our sample application is complete. You should be able to run this application by entering the following in your browser:

http://yourdomain.com/reviews/show/1

This will call the reviews controller that we created in Step 4.3, and call its show() method with an input parameter 1. This parameter is taken as the ID of the movie; this will be used to fetch database information about the movie with an ID = 1. As a result, the user should now see the title and review the grade of the first movie in the database.

Conclusion

There you have it, folks. In this in-depth CodeIgniter tutorial, we saw what it is, how to install and configure it, as well as build a very simple application using the framework. We also looked at MVC – the guiding principle behind CodeIgniter and why it’s so useful in modern web development.

While our sample application was extremely simple, with only one model, view and controller each, and a singular database query, we hope that it served its goal of letting the user become familiar with the core of CodeIgniter’s functionality.

Readers can now build highly dynamic, scalable and feature-laden applications using CodeIgniter, faster than before, by using the framework’s libraries and helpers on offer. We hope you all saw just how simple yet powerful CodeIgniter is, and wish you the best on your web development journey with PHP’s darling framework.