Code­Igniter serves as a web ap­plic­a­tion framework for de­velopers who prefer speed over an abundant range of functions. The main design goal of this open source PHP framework, according to the official project site, is to combine maximum per­form­ance and flex­ib­il­ity with the smallest possible programme framework.

What is Code­Igniter?

Code­Igniter is a web framework written in PHP that prides itself on making the de­vel­op­ment of web ap­plic­a­tions faster and more efficient by using a compact software design. The U.S. software company EllisLab created Code­Igniter. The first version was released in February 2006. On July 13, 2013 they announced that they would no longer be able to provide the necessary resources for further de­vel­op­ment of the software. One year later the project was taken over by the British Columbia Institute of Tech­no­logy (BCIT). The source code of the framework is under the MIT license and can be obtained via the online service GitHub. The most current stable version Code­Igniter 3.1.3 is available for free download on the project’s official website.

Makeup and structure of the framework

The per­form­ance-oriented design of Code­Igniter is reflected in the lean structure of the PHP framework. This is based on the software ar­chi­tec­ture pattern Model View Con­troll­ter (MVC). The basic principle behind MVC is the strict sep­ar­a­tion of programme code and present­a­tion. This is ac­com­plished through a modular software structure and the out­sourcing of PHP code. There are three central com­pon­ents: the data model (Model), the present­a­tion (View), and the con­trol­ler (Con­trol­ler).

  • The data model (Model) rep­res­ents the data structure of a web ap­plic­a­tion developed on the basis of Code­Igniter. For this purpose, model classes are defined in the source code. These include special functions with which in­form­a­tion from a database can be accessed, stored, or updated.
  • The present­a­tion (View) is the part of the ap­plic­a­tion that is presented to users. As a rule, this is an HTML document in which content is dy­nam­ic­ally in­teg­rated via PHP. A view is basically a kind of template. Code­Igniter provides the op­por­tun­ity to define webpage elements like the header and footer or RSS-sites in the view. Generally, web ap­plic­a­tions use multiple views to refer to content using the same data model. This allows different programme features to be presented in different views.
  • The con­trol­ler (Con­trol­ler) serves as a mediating entity between the model, view, and any other resource that is required to process an HTTP request or dy­nam­ic­ally generate a website. This component takes inbound requests, validates the input, selects the desired view, and passes on content that the data model has loaded from a database.

The following graphic shows the interplay between the MVC com­pon­ents in a schematic rep­res­ent­a­tion:

The MVC structure enables a flexible software design in which in­di­vidu­al programme modules can be exchanged, revised, and reused with minimal effort. Changes to a component have no impact on the source codes of the other com­pon­ents (provided no changes are made to the in­ter­faces).

The strict sep­ar­a­tion between programme logic and present­a­tion provides for a clear, well-struc­tured programme code. Web ap­plic­a­tions based on MVC are con­sidered to be main­ten­ance friendly. In the case of an error, the search for its source is usually limited to just one of the com­pon­ents.

The MVC ar­chi­tec­tur­al model also allows for the separate de­vel­op­ment of a web ap­plic­a­tion’s logic and layout. Back-end and front-end de­velopers work in parallel, and ap­plic­a­tions can be completed much faster.

Code­Igniter makes use of MVC, but doesn’t bind users com­pletely to this ar­chi­tec­tur­al model. While it requires the use of the con­trol­ler and view com­pon­ents, con­nec­tions to databases via the model component are optional. Ad­di­tion­ally, an ap­plic­a­tion based on Code­Igniter can also be carried out using a hier­arch­ic­al MVC ar­chi­tec­ture (HMVC), which follows the classic MVC format but adds a hier­arch­ic­al component.

The ap­plic­a­tion flow of PHP frame­works

Code­Igniter is based on a URL concept. That means that the con­trol­ler, as the central control unit between the view and the model, is accessed by entering a URL into the search bar of the web browser. De­velopers create so-called con­trol­ler classes. These are PHP files that contain various functions used to load libraries, plugins, or helpers, connect to databases, integrate a data model, or search for a specific view.

The ap­plic­a­tion flow of Code­Igniter is based on the following URL structure:

                example.com/class/function/parameter

The domain (example.com) is followed by a con­trol­ler class, that should be addressed, as well as a par­tic­u­lar con­trol­ler function. The end forms the optional para­met­ers. These are used to deliver the con­trol­ler IDs or variables.

In theory, a Code­Igniter URL could look like this:

                example.com/news/article/511

Such a URL addresses the con­trol­ler news on the domain example.com and prompts the function article to be executed (for example, loading a view of the same name for present­a­tion of the article). Which contents of the data model should be retrieved from the database and which are passed to the con­trol­ler via the URL  are optional para­met­ers – in this example an article with the ID 511.

In the output con­fig­ur­a­tion, Code­Igniter quotes index.php in every ap­plic­a­tion URL:

                example.com/index.php/news/article/511

This PHP file contains in­form­a­tion about where to find the core files of the framework. It also helps you find in­teg­rated libraries, plugins, or helpers as well as in which index the ap­plic­a­tion files are contained. The index.php is used to ini­tial­ise all base resources.

If Code­Igniter runs on the Apache HTTP server then the index.php and mod_rewrite can be removed from the ap­plic­a­tion URL to make a “clean” web address available for the end users and search machine crawlers. De­velopers insert the following code block into the .htaccess file of the web server:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

The basic structure of the PHP framework primarily supports the con­trol­ler classes, model classes, and view templates.

Con­trol­ler classes

Code­Igniter gives de­velopers the op­por­tun­ity to programme in­di­vidu­al con­trol­lers as user defined classes. Web de­velopers create a separate PHP file for each con­trol­ler in the index ap­plic­a­tion/con­trol­lers/. Con­trol­lers contain the programme logic of a web ap­plic­a­tion developed with Code­Igniter and are created as sub­classes of the CI_Con­trol­ler class. In the source code, pro­gram­mers do this using the extends keyword.

class News extends CI_Controller {
}

As a subclass, News inherits all of the vis­ib­il­ity public and protected functions from the parent class CI_Con­trol­ler.

Note

The keywords public, protected, or private serve in PHP to define the vis­ib­il­ity of a feature or function. If an element is declared as public, all classes in a software have access to that element. If this access is re­stric­ted to the parent classes and derived classes, pro­gram­mers use the keyword protected. An element that is declared as private only is available to the class that the element defines.

Every user defined con­trol­ler class has to contain a con­struct­or function with which libraries, a data model, databases, or helper classes can be in­teg­rated. Since PHP5 __construct() has been used as the standard con­struct­or function.

<?php
class News extends CI_Controller {
    public function __construct() {        //defines the constructor
        parent::__construct();        //retrieves the constructor of the parent class    
        $this->load->helper('url');        //loads a helper class for working with URLs
        $this->load->helper('file');     //loads a helper class for working with the files
        $this->load->database();        //loads a database
        $this->load->model('News_model');    //loads a model with the name “News_model”
}
?>

The example shows the class News as the subclass of CI_Con­trol­ler. The con­struct­or function __construct() in­teg­rates two helper classes, a database, and the data model News_model. The in­di­vidu­al code lines are excerpted in the source text.

Note

All con­trol­ler classes that are defined for Code­Igniter in PHP have to start with a capital letter (News instead of news). In the URL, though, they can be written in lower-case.

Con­trol­ler functions

If the basic framework for user defined con­trol­lers is located, the actual programme logic follows in the form of con­trol­ler functions with which views can be retrieved or in­ter­ac­tions with an in­teg­rated data model can be carried out.

In order for a con­trol­ler to load a view, the un­der­ly­ing HTML document must be stored as a PHP file in the ap­plic­a­tion/views/ index. A simple view for article present­a­tion could, for example, look like so:

<!DOCTYPE html>
<html lang="de">
  <head>
    <meta charset="utf-8">
    <title><?php echo $title; ?></title>
 </head>
 <body >
    <h1><?php echo $headline ?></h1>
    <p><?php echo  $content_body ?></p>
 </body>
</html>
Note

HTML documents that contain PHP code must be saved as PHP files (.php). This is the only way to make sure that the PHP in­ter­pret­er of the web server runs scripts instead of out­put­ting the PHP code as text.

To load a view in the con­trol­ler, a user defined function is needed. The following code example uses the article() function to load the article.php view.

public function article() {
    if (!file_exists(application/views/article.php)) {
        show_404();
    }
$this->load->view('article');
}

The programme code reads as follows: first, Code­Igniter tests whether the index ap­plic­a­tion/views/ contains a file with the name article.php. This inquiry is im­ple­men­ted through the language construct if and the negative (!) command file exists().

If the condition is met and the command finds no file by that name in the cor­res­pond­ing index, then if returns the value TRUE and Code­Igniter executes the function show_404(), which is listed under if. In this case, a user receives the notice that the requested file doesn’t exist. But if the if command isn’t fulfilled and the !file_exists is evaluated as FALSE, then Code­Igniter initiates the function $this->load->view(‘article’). This is used to load the cor­res­pond­ing file as a view into the ap­plic­a­tion.

As long as it’s in PHP format, the desired data can be listed in the view() function without a suffix. If other formats are being loaded, then the re­spect­ive file suffix is ob­lig­at­ory.

Code­Igniter is usually used as part of dynamic web ap­plic­a­tions. These display dy­nam­ic­ally generated webpages to users instead of static HTML sites. This can be done by filling the view with data that matches the para­met­ers passed to Code­Igniter via the URL.

                example.com/news/article/511

Until now, the only view for article display was loaded with the function  $this->load->view('article'). But now it’s necessary to spe­cific­ally integrate the contents that are linked to the parameter 511. We assume that this is an ID that’s linked to a par­tic­u­lar news item using a database man­age­ment system. To load it from the database into the programme, the above example needs to be sup­ple­men­ted so that the data model embedded in the con­struct­or is addressed.

public function article($id) {
    if (!file_exists(application/views/article.php)) {
        show_404();
    }
    $data = $this->News_model->get_data($id);
    $this->load->view('article', $data);}

The delivered function argument (here under the variable name $id) cor­res­ponds to the ID part of the URL – for example, 511. The yet-to-be-written model function get_data() is used to load the article content linked to the ID from the database. The view() method invokes the article view and delivers the data to it in the form of an as­so­ci­at­ive array ($data). The data model News_model also delivers the data to the News con­trol­ler, which passes it on to the view.

All op­er­a­tions as­so­ci­ated with data fetching are trans­ferred to the embedded data model.

Model classes

Data models are used by Code­Igniter to provide functions that can be used to perform certain database op­er­a­tions. Exactly like con­trol­ler classes, model classes are pro­grammed using the user defined PHP framework.

To create a model class, first you have to create a class name – in this case, News_model. Similar to con­trol­ler classes, all user defined model classes are sub­classes of the parent class CI_Model. The in­her­it­ance is im­ple­men­ted through the extends keyword. Model classes also in­cor­por­ate databases and other resources with the con­struct­or function.

class News_model extends CI_Model {
    public function __construct() {
        parent::__construct();
        $this->load->database(); 
    }
}

Model functions follow this basic structure, in which de­velopers define all database op­er­a­tions that should be available to the con­trol­ler via the re­spect­ive data model.

Model functions

Model classes enable de­velopers to define in­di­vidu­al functions for database op­er­a­tions. In the above example, we utilised the user defined function get_data() in the con­trol­ler class News to load article content from the database into the view. In the model, we only define which database op­er­a­tions are hidden behind the function.

class News_model extends CI_Model {
    public function __construct() {
        parent::__construct();
        $this->load->database(); 
    }
public function get_data($id) {
     $this->db->select('content');
     $this->db->from('example_table');
     $this->db->where('id', $id);
    $query = $this->db->get();
    return $query->result();
}

In the model class News_model the above function get_data() is defined as a database operation, which is the column of the data set specified by select() with the delivered ID number ($id) from the database table specified by from() and returned via get() with the help of the function result() as an array. A data model typically provides a variety of model functions. De­velopers can draw on the query builder class, which includes a set of pre­defined functions for classic database op­er­a­tions. An overview can be found in the official doc­u­ment­a­tion of Code­Igniter frame­works.

Routing with Code­Igniter

Which control class and function should be addressed are given to Code­Igniter with a URL. To do this, the web framework uses the URL structure class/function/parameter. This basic structure can be adapted as required. Code­Igniter provides the file routes.php in the ap­plic­a­tion/config/ index for this purpose. This contains an array called $route that enables de­velopers to define their own routing criteria.

In the output con­fig­ur­a­tion of the $route array there are three default entries: the standard con­trol­ler, a routing rule for the 404 override, and a rule for the automatic re­place­ment of hyphens (-) with un­der­scores (_).

$route['default_controller'] = 'home/welcome';
$route['404_override'] = 'home/welcome';
$route['translate_uri_dashes'] = FALSE;

The first default entry provides the standard con­trol­ler of the ap­plic­a­tion. This is loaded by Code­Igniter whenever a URL other than the domain contains no further routing in­form­a­tion. In the current example the routing rule defines the con­trol­ler class home as the standard con­trol­ler. Visitors who don’t specify the target webpage in the URL are therefore re­dir­ec­ted to home and presented with the welcome view. Usually this is a re­dir­ec­tion to the start page. If no con­trol­ler is defined as the standard then Code­Igniter shows a 404-error page when the start page is called.

The second default entry in the $route array defines a con­trol­ler that can be called when the con­trol­ler addressed by the URL isn’t found in the ap­plic­a­tion files. The routing rule $route[‘404_override’] = ‘home’ over­writes the 404-error page that would normally be shown in such a case, and instead leads to the con­trol­ler class home.

The third default entry in the $route array prevents routing errors based on hyphens. The hyphen isn’t a validate character for class or function names and is auto­mat­ic­ally replaced in URLs in the default settings.

To create a user defined routing rule for a dynamic URL the web developer has two available options with Code­Igniter: Routing entries for dynamic URLs can be defined with Wildcards (place­hold­ers) or with regular ex­pres­sions.

routes.php supports two types of wildcards:

Note

Websites with a large number of 404-error pages are difficult to crawl and make it hard for search engines to access relevant data. In addition to the impact on user ex­per­i­ence this can have a negative influence on the ranking in search engines. As a rule web de­velopers should endeavor to avoid 404-error pages.

Wildcards of routes.php De­scrip­tion
:num Functions as a place­hold­er for integers (whole numbers)
:any Functions as a place­hold­er for a string (char­ac­ters)

The following example shows an entry in routes.php that enables the function (article) to be deleted from the URL:

$route['news/article/(:num)'] = 'news/$1';

The wildcard :num reads the parameter of a dynamic URL and stores it in the variable $1. If you define routing rules with :num or :any then you have to put them in simple brackets with routes.php.

routes.php also accepts routing rules in the form of regular ex­pres­sions. The two place­hold­er types can also be noted as follows:

:num corresponds to \d+
:any corresponds to [^/]+

An al­tern­at­ive to the above example would be the following notation:

$route['news/article/(\d+ )'] = 'news/$1';

Regular ex­pres­sions are also put in brackets with routes.php.

An overview of ap­plic­a­tion flow

The following graphic outlines the flow of an ap­plic­a­tion on the basis of Code­Igniter in seven steps:

1. Code­Igniter uses index.php as a front con­trol­ler for incoming HTTP requests. All basic resources needed to run the ap­plic­a­tion are ini­tial­ised here.

2. As part of the routing, Code­Igniter checks which action is to be carried out. For this purpose, the ap­plic­a­tion compares the URL in the request with the routing rules defines in routes.php.

3. Routing is followed by caching. If a response matching a request is count in the ap­plic­a­tion’s cache it’s delivered directly to the re­quest­ing web browser. Otherwise, the con­trol­ler de­term­ined during routing is executed with a preceding filter function.

4. The Code­Igniter framework contains an in­teg­rated filter that in­ter­cepts harmful inquiries. Before the ap­plic­a­tion loads a con­trol­ler matching the request, every HTTP request undergoes a security check.

5. If the request passes the filter, then the con­trol­ler is executed. This selects a matching view and loads the data model as well as all libraries, helper classes, plugins, and scripts needed to answer the query.

6. As soon as all of the relevant data has been passed to the view, it can be delivered to the web browser.

7. If a caching is activated, Code­Igniter tem­por­ar­ily stops outgoing data to be able to directly answer re­pet­it­ive queries.

Benefits of the Code­Igniter framework

With more than 13,000 stars, Code­Igniter is a highly respected GitHub de­vel­op­ment project and ranked 3rd among the most popular PHP frame­works. The benefits of the ap­plic­a­tion are as follows:

Minimal con­fig­ur­a­tion effort: Code­Igniter is quick to get started. Users aren’t delayed for long with the con­fig­ur­a­tion of the framework and can instead begin with the de­vel­op­ment of the planned ap­plic­a­tion almost im­me­di­ately after the in­stall­a­tion. The con­fig­ur­a­tion effort is es­sen­tially re­stric­ted to the settings in config.php and the ap­plic­a­tion/config/ index. Here, users define a standard path for web browser access, a key for en­cryp­tion, a name for session cookies, and settings for cross-site scripting (XSS). It is also re­com­men­ded to create an .htaccess file to remove index.php from the path of ap­plic­a­tion URLs via Re­writeR­ule.  A database con­nec­tion con­fig­ur­a­tion is also necessary, which you enter into the database.php file.

  • Small footprint: Code­Igniter leaves a small footprint behind in your system. The download pack of the framework spans around 11MB. More than 9MB of which is due to the detailed doc­u­ment­a­tion of the software. The minimal amount of code is due to the fact that the Code­Igniter basic system only contains a few small libraries. Ad­di­tion­al resources can be loaded as required.
  • Excellent per­form­ance: The lean core system means that Code­Igniter can score a higher speed in com­par­is­on to other PHP frame­works. The system was praised by the PHP inventor Rasmus Lerdorf, among others. In 2008, the Free and Open Source Con­fer­ence (FrOSCon) he announced that he liked Code­Igniter “because it is faster, lighter, and the least like a framework.”
  • “Clean” URLs: Code­Igniter auto­mat­ic­ally generates user friendly, search machine ap­pro­pri­ate URLs. Instead of accessing dynamic web content through query strings like other PHP frame­works, Code­Igniter uses a segment-based approach.

URL with query string: example.com?con­trol­ler=news&function=article&id=511

Segment-based URL: example.com/news/article/511

  • Free pro­gram­ming style: Code­Igniter is based on a free in­ter­pret­a­tion of MVC ar­chi­tec­tur­al structure. There is no set pro­gram­ming style for de­velopers.
  • Extensive doc­u­ment­a­tion: Code­Igniter has a detailed doc­u­ment­a­tion in English, including a beginner’s tutorial in which the source code is clearly and well com­ment­ated. The Code­Igniter doc­u­ment­a­tion is on the project website as an online guide as well as an available version for download.
  • Community support: De­velopers who build their ap­plic­a­tions on the basis of Code­Igniter can support them­selves with help from other users. The project is ac­com­pan­ied by an active community. A public forum can be found on https://forum.code­igniter.com. Currently, more than 7,300 users are involved in exchanges over the de­ploy­ment and further de­vel­op­ment of the framework in about 65,000 threads.

Drawbacks of the Code­Igniter framework

Since the de­vel­op­ment of the Code­Igniter framework stagnated before the takeover by the BCIT took place, de­velopers searched for tech­no­lo­gic­al im­prove­ments that had been adapted by com­par­able frame­works in recent years but were un­suc­cess­ful with Code­Igniter.

  • ORM only through third parties: Object Re­la­tion­al Mapping (or ORM) describes a technique of software de­vel­op­ment that allows ap­plic­a­tions to store objects written in an object-oriented pro­gram­ming language such as PHP in a re­la­tion­al database. Code­Igniter doesn’t natively support ORM, so the technique can only be in­teg­rated through a third party.
  • No template engine: Code­Igniter prides itself on func­tion­ing without a template engine. Instead, the framework provides optional simple template parser. This can be seen as a benefit as the use of a template engine usually comes with a per­form­ance overhead (ad­di­tion­al expense at runtime). In addition to the framework the use of the template language also has to be learned. But a template engine does allow for the sep­ar­a­tion of the data gen­er­a­tion from the code for the present­a­tion, which usually leads to a clearly struc­tured source code. If a template engine with slim syntax is used, this can sig­ni­fic­antly reduce the overall volume of the ap­plic­a­tion code.
  • No namespa­cing: With namespace, PHP allows you to separate code from different ap­plic­a­tion groups. PHP de­velopers use this feature to avoid conflicts that can come up when naming classes and functions. For example, naming col­li­sions with internal PHP classes, functions, constants, or elements in­teg­rated by a third party are common. Code­Igniter doesn’t use namespa­cing anymore.
  • No PHP auto-loading: Since Version 5, PHP offers the functions __autoload() and spl_autoload_register() that allow required class defin­i­tions to be loaded auto­mat­ic­ally. The Code­Igniter framework doesn’t utilise this feature.
  • Fewer built-in libraries than other PHP frame­works: Because of the lean software design, Code­Igniter offers sig­ni­fic­antly fewer libraries in the output con­fig­ur­a­tion than other PHP frame­works. These primarily include the most important tasks of web de­vel­op­ment like database access, e-mailing, val­id­a­tion of form data, main­ten­ance of sessions, or working with XML-RPC. For tasks that go beyond the scope of the basic features you have to integrate your own libraries or resources from a third party. This is a point that de­velopers who are looking for a minimised framework can also interpret as an advantage.

Code­Igniter for the hurried reader

The table below provides an overview of the basic in­form­a­tion of the Code­Igniter framework:

Code­Igniter
Developer British Columbia Institute of Tech­no­logy (BCIT)
Current release Version 3.1.2
Design pattern MVC/HMVC, Active Record, Chain of Re­spons­ib­il­ity
Necessary knowledge PHP, Object-Oriented Pro­gram­ming (OOP)
Pro­gram­ming language PHP 5.6 or higher
License MIT License
Database support MySQL (5.1+), Oracle, Post­gr­eSQL, MS SQL, SQLite, CUBRID, Interbase/Firebird, ODBC
ORM Only through third parties
Caching Yes
Template engine No
Namespaces No
PHP auto-loading No
Search machine-friendly URLs No
Security features Cross-Site-Request-Forgery (XSRF), Cross-Site-Scripting (XSS), SQL-Injection
Testing library PHP Unit

Con­clu­sion: Which projects are suitable for Code­Igniter?

With its compact design and user-friendly syntax Code­Igniter is best suited for the pro­spect­ive pro­gram­mer. Anyone who has already had some ex­per­i­ence with dynamic web de­vel­op­ment based on PHP will also become familiar with the PHP-based light­weight framework pretty quickly. Ex­per­i­enced pro­gram­mers will also ap­pre­ci­ate the flex­ib­il­ity that allows them basic func­tion­al­ity with a reduced PHP framework. But if you want to use Code­Igniter, you should be familiar with the MVC ar­chi­tec­tur­al structure and be able to do without a template engine as well as native ORM. Despite the minimal code range Code­Igniter is equally suitable for small and large web projects.

Go to Main Menu