Development and Managed Hosting
ANEXIA
FEB
27
2015

Quickstart to the CodeIgniter framework

Written on February 27, 2015 by Manuel Wutte

What is CodeIgniter? In CodeIgniter is an open source web framework written in PHP (Open Software License 3.0), which enjoys great popularity especially in America.

codeigniter_logo

 

It was developed by the software development company EllisLab, which is located in the US state of Oregon. The first public release of the framework was published on 28 February 2006.

CodeIgniter touts trying to be much faster and more efficient compared with other web frameworks. The development time of new software and web applications will be reduced considerably.

In a critical view of PHP frameworks in general the PHP creator Rasmus Nerdorf mentioned at FrOSCon in August 2008 that he likes CodeIgniter, because it’s “faster, lighter and the least like a framework”.

However, in recent times the development team of EllisLab wasn’t able to muster the resources that would have been necessary for further development. On July 9, 2013 EllisLab finally published a blog article in which they announced that from now a new “home” for the CodeIgniter framework is being sought.

The latest stable release (version 2.2.0) was released on June 5, 2014. This version is currently also the latest.

On October 6, 2014 was finally announced that the “British Columbia Institute of Technology” (BCIT) from Vancouver (Canada) has completely taken over the project.

The source code is available on GitHub under the MIT license, where currently actively on version 3.0 is being worked.

 

Design and structure

The fact that CodeIgniter was deliberately kept as slim as possible, the framework is distinguished compared to other mainly by a high performance, and has analogous to that a relatively short training period.

To make the code more concise and easy to maintain, CodeIgniter is based on the Model-View-Controller architecture (MVC).

The basic idea behind MVC is the one that you want to strictly separate program code and design from each other, so that the software in general is more modular. So backend-developers can take care of the technical program logic and front-end designers to lay out and the individual graphical components, for example. This parallel operation also contributes significantly to the rapid development time of new software.

CodeIgniter comes by default with a comprehensive set of libraries and various auxiliary functions on board to support the developer with frequently used functions, ranging from the database communication, the input validation and also for implementing a shopping cart system.

Of particular note here is the easy configuration. In most cases, it is quite sufficient to configure only a database connection and possibly a base URL.

 

From theory to practice – an example

To give you a little insight into the software development based on the CodeIgniter framework, I will demonstrate you the basic functions on the basis of a small and highly simplified example project.

I’m going to build a small job board where you can add jobs, which will be displayed in a list. By clicking on the job offer you’ll be getting into the detail view. If required, the offers can be deleted afterwards again.

First of all we need to download the framework from the homepage or directly from GitHub. I’m using the latest stable version 2.2.0 (here “CodeIgniter-2.2.0.tar.gz”).

We then have to extract the contents and copy all directories and files to a new folder on the development server (e.g. XAMPP, WAMP, LAMP…). I name this folder here simply “ci-demo”.

Now we can test whether the CodeIgniter installation is working – we’re accessing the demo setup via http://localhost/ci-demo. You should now see the welcome screen (“Welcome to CodeIgniter”).

In theory, we could get started with developing immediately, but I recommend you to integrate the official layout library before. This will save us a lot of work later and it will make the code even more clearly.

To do this we proceed as follows: on the GitHub wiki page we’ll find the necessary PHP code. We create a new file called “layout.php” and copy the source code into it. Afterwards we save this into /application/libraries.

The next step is to configure CodeIgniter so that this library is always be loaded by default. To do this we open the file /application/config/autoload.php and look for the following expression:

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

To this array we now add the libraries for the layout and the database so that it’s then looking like this:

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

Thus, we can use some utility functions later, we’re also loading the URL and the form helper:

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

At /application/views we create a new file “layout_main.php” (this is the default layout, which is initialized by the layout library). In this we describe our basic HTML structure. It’s important that we have to echo the PHP variable $content_for_layout at the point where we want to display the View-specific content!

<html>
	<head>
		<title>CodeIgniter Demo</title>
	</head>
	<body>
		<div id="header">
			<h1>CodeIgniter Demo</h1>
			<hr />
		</div>

		<div id="main">
			<?php echo $content_for_layout; ?>
		</div>

		<div id="footer">
			<hr />
			Footer...
		</div>
	</body>
</html>

For producing nice “speaking URLs” without the “index.php” between, we create a new file called “.htaccess” in the root directory of CodeIgniter (Apache as web server required!) and write the following lines in there:

RewriteEngine on
RewriteRule .* index.php

Now we have created all the basic requirements, so you can start with the actual development.

Since we want to recreate a kind of “job board” here, we have to create first a new controller. I’ll name this “jobs”, and accordingly create a new file “jobs.php” located at /application/controllers.

class Jobs extends CI_Controller {
	
	public function index()
	{
		$this->load->view('/jobs/index');
	}
}

Since we want to use our layout library here, loading the view must be adjusted slightly. To do this we change the following line from

$this->load->view('/jobs/index');

to

$this->layout->view('/jobs/index');

So we have the advantage that there isn’t always the need of loading the layout of the header, followed by the actual content and the footer in each action – this is now managed by the layout library for us so we can fully concentrate on the actual content itself.

Next, we have to create our View. To do this we create in /application/views a new folder called “jobs” and inside this a new file “index.php“. This is not mandatory, but promotes clarity when using several controllers.

The index action will be used later for the listing all the jobs. For adding job offers, viewing and deleting them, we need to create the actions “add”, “view” and “delete” (here no View necessary) on the same principle.

This is how the jobs controller finally looks like:

class Jobs extends CI_Controller {
	
	public function index()
	{
		$this->layout->view('/jobs/index');
	}

	public function add()
	{
		$this->layout->view('/jobs/add');
	}

	public function delete(){ }

	public function view()
	{
		$this->layout->view('/jobs/view');
	}
}

Now we are done with the basic structure, it will be time for connection to the database. For this, we create a new MySQL table called “jobs”:

CREATE TABLE IF NOT EXISTS `jobs` (
	`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
	`title` varchar(255) NOT NULL,
	`company` varchar(255) NOT NULL,
	`description` text NOT NULL
);

In the configuration file for the database driver located at /application/config/database.php we configure the credentials for the MySQL server and also the name of the database.

For accessing the database from inside the controller we need a so called “Model”. This will provide us functions, which we call from the controller, to receive so to data of the database.

CodeIgniter uses the “ActiveRecord” ORM. Instead of writing the SQL statements directly, we use here predefined functions, which we’ll call from the controller. So we are getting an abstraction layer and we are independent of the database driver. The ORM is generating the necessary statements dynamically and returns the responses from the database as objects.

For our job board model we create a new file “jobs_model.php” at /application/models and declare here our methods. One should be used for returning all entries, another one however should only return a single entry (by ID), and finally another ones for adding and deleting of an entry.

class Jobs_model extends CI_Model {

	protected $table = 'jobs';
	
	// returns all job offers
	public function getAll()
	{
		$result = $this->db->get( $this->table )->result_object();	
		return $result;
	}
	
	// looks for job offer by id
	public function getById($id)
	{
		$this->db->select('*')
				->from( $this->table )
				->where('id', (int) $id);
				
		$result = $this->db->get()->row_object();
		
		return $result;
	}

	// add job offer
	public function add(array $data)
	{
		return $this->db->insert( $this->table, $data);
	}

	// deletes job offer
	public function delete($id)
	{
		$this->db->delete( $this->table, array('id' => (int) $id));
	}
}
Hint: result_object() returns an array with multiple entries (as objects), however row_object() return only the requested object. As alternative to the objects-format you can use the array-format via result_array() and row_array().

Inside the jobs controller we firstly load this Model by initializing it in the constructor. For this, we append the following piece of code to the controller:

public function __construct()
{
	parent::__construct();
	$this->load->model('jobs_model');
}

Now we can use the jobs Model and its methods via $this->jobs_model.

Thus, the index action will be listing the job offers, we call the model method “getAll()“, and pass the return value to the view.

public function index()
{
	$data = array(
		'jobs' => $this->jobs_model->getAll(),
	);
	
	$this->layout->view('/jobs/index', $data);
}

In In the view we can now print the job by using the variable $jobs:

<h2>Overview</h2>

<a href="<?php echo base_url(); ?>jobs/add">Add new</a>

<table>
	<thead>
		<th>Title</th>
		<th>Company</th>
		<th>Action</th>
	</thead>
	<tbody>
	
		<?php foreach($jobs as $job): ?>
		<tr>
			<td><?php echo $job->title; ?></td>
			<td><?php echo $job->company; ?></td>
			<td>
				<a href="<?php echo base_url() . 'jobs/view/'. $job->id; ?>">View</a> 
				<a href="<?php echo base_url() . 'jobs/delete/'. $job->id; ?>">Delete</a>
			</td>
		</tr>
		<?php endforeach; ?>
	
	</tbody>
</table>

So that we’re able create a job offer we have to change our add-view as follows (for simplicity, the form elements here weren’t created by the form helper!):

<a href="<?php echo base_url(); ?>jobs">&laquo; Back</a>

<h2>Add new job offer</h2>

<?php echo form_open(); ?>

<table>
	<tr>
		<td>Title:</td>
		<td><input type="text" name="title" /></td>
	</tr>
	<tr>
		<td>Company:</td>
		<td><input type="text" name="company" /></td>
	</tr>
	<tr>
		<td>Description:</td>
		<td><textarea name="description"></textarea></td>
	</tr>
	<tr>
		<td></td>
		<td><input type="submit" value="Save" /></td>
	</tr>
</table>

<?php echo form_close(); ?>

The corresponding action then looks as follows:

public function add()
{
	$post = $this->input->post(NULL, TRUE);
	
	if($post) {
		$data = array(
			'title'		=> $post['title'],
			'company'		=> $post['company'],
			'description'	=> $post['description'],
		);
			
		$this->jobs_model->add($data);
		
		redirect('jobs');
	} else {
		$this->layout->view('/jobs/add');
	}
}

If a POST request is made, a new record will be saved, otherwise the form is being displayed.

In the Action for deleting we don’t use any user confirmation for the sake of simplicity – we delete the entry directly.

public function delete($id)
{
	$this->jobs_model->delete($id);	
	redirect('jobs');
}

In practice, however, I recommend that such actions must be implemented via POST, as this is safer! A server-side validation shouldn’t be missed (e.g. whether the user is authorized to do so…)!

For the detail view the controller must pick only the corresponding entry from the database and pass it to the view:

public function view($id)
{
	$data = array(
		'job' => $this->jobs_model->getById($id),
	);
	
	$this->layout->view('/jobs/view', $data);
}

The view is basically the same as those of the add-action, except that instead of the input fields the data from the database is being displayed:

<a href="<?php echo base_url(); ?>jobs">&laquo; Back</a>

<h2>Details: <?php echo $job->title; ?></h2>

<table>
	<tr>
		<td>Title:</td>
		<td><?php echo $job->title; ?></td>
	</tr>
	<tr>
		<td>Company:</td>
		<td><?php echo $job->company; ?></td>
	</tr>
	<tr>
		<td>Description:</td>
		<td><?php echo nl2br($job->description); ?></td>
	</tr>
</table>

Thus we have finished the demo project and by the way have met the most relevant basic functions.

Those who want to change the default controller, so that when accessing http://localhost/ci-demo not the CodeIgniter welcome screen is shown, but instead the job board.

For this purpose, we change the routes.php file in /application/config the following line from

$route['default_controller'] = "welcome";

to

$route['default_controller'] = "jobs";

 

Conclusion

The CodeIgniter framework features in comparison to other PHP frameworks by a very high performance and ease.

The fact that it was kept relatively light on the features, it offers the developer all possibilities, because it lets your creativity run wild. Similarly, you will unconsciously be moved to a consistent way of adhering to structures.

This kind of software development allows the developer maximum freedom, but manages to keep the code readable at all times and thereby also easy to maintain.

Important to mention is primarily the frameworks’ large community, as well as a good and extensive documentation, with many little examples.

In my opinion, CodeIgniter is particularly suitable for the implementation of small up to medium-scale projects.

 

Official homepage: http://www.codeigniter.com