CodeIgnit­er serves as a web ap­pli­ca­tion framework for de­vel­op­ers 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­for­mance and flex­i­bil­i­ty with the smallest possible program framework.

What is CodeIgnit­er?

CodeIgnit­er is a web framework written in PHP that prides itself on making the de­vel­op­ment of web ap­pli­ca­tions faster and more efficient by using a compact software design. The U.S. software company EllisLab created CodeIgnit­er. 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­nol­o­gy (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 CodeIgnit­er 3.1.3 is available for free download on the project’s official website.

Makeup and structure of the framework

The per­for­mance-oriented design of CodeIgnit­er 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­a­ra­tion of program code and pre­sen­ta­tion. This is ac­com­plished through a modular software structure and the out­sourc­ing of PHP code. There are three central com­po­nents: the data model (Model), the pre­sen­ta­tion (View), and the con­troller (Con­troller).

  • The data model (Model) rep­re­sents the data structure of a web ap­pli­ca­tion developed on the basis of CodeIgnit­er. For this purpose, model classes are defined in the source code. These include special functions with which in­for­ma­tion from a database can be accessed, stored, or updated.
  • The pre­sen­ta­tion (View) is the part of the ap­pli­ca­tion that is presented to users. As a rule, this is an HTML document in which content is dy­nam­i­cal­ly in­te­grat­ed via PHP. A view is basically a kind of template. CodeIgnit­er provides the op­por­tu­ni­ty to define webpage elements like the header and footer or RSS-sites in the view. Generally, web ap­pli­ca­tions use multiple views to refer to content using the same data model. This allows different program features to be presented in different views.
  • The con­troller (Con­troller) serves as a mediating entity between the model, view, and any other resource that is required to process an HTTP request or dy­nam­i­cal­ly 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­po­nents in a schematic rep­re­sen­ta­tion:

The MVC structure enables a flexible software design in which in­di­vid­ual program 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­po­nents (provided no changes are made to the in­ter­faces).

The strict sep­a­ra­tion between program logic and pre­sen­ta­tion provides for a clear, well-struc­tured program code. Web ap­pli­ca­tions based on MVC are con­sid­ered to be main­te­nance friendly. In the case of an error, the search for its source is usually limited to just one of the com­po­nents.

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

CodeIgnit­er makes use of MVC, but doesn’t bind users com­plete­ly to this ar­chi­tec­tur­al model. While it requires the use of the con­troller and view com­po­nents, con­nec­tions to databases via the model component are optional. Ad­di­tion­al­ly, an ap­pli­ca­tion based on CodeIgnit­er can also be carried out using a hi­er­ar­chi­cal MVC ar­chi­tec­ture (HMVC), which follows the classic MVC format but adds a hi­er­ar­chi­cal component.

The ap­pli­ca­tion flow of PHP frame­works

CodeIgnit­er is based on a URL concept. That means that the con­troller, 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­vel­op­ers create so-called con­troller 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­pli­ca­tion flow of CodeIgnit­er is based on the following URL structure:                 example.com/class/function/parameter The domain (example.com) is followed by a con­troller class, that should be addressed, as well as a par­tic­u­lar con­troller function. The end forms the optional pa­ra­me­ters. These are used to deliver the con­troller IDs or variables. In theory, a CodeIgnit­er URL could look like this:                 example.com/news/article/511 Such a URL addresses the con­troller news on the domain example.com and prompts the function article to be executed (for example, loading a view of the same name for pre­sen­ta­tion of the article). Which contents of the data model should be retrieved from the database and which are passed to the con­troller via the URL  are optional pa­ra­me­ters – in this example an article with the ID 511. In the output con­fig­u­ra­tion, CodeIgnit­er quotes index.php in every ap­pli­ca­tion URL:                 example.com/index.php/news/article/511 This PHP file contains in­for­ma­tion about where to find the core files of the framework. It also helps you find in­te­grat­ed libraries, plugins, or helpers as well as in which index the ap­pli­ca­tion files are contained. The index.php is used to ini­tial­ize all base resources. If CodeIgnit­er runs on the Apache HTTP server then the index.php and mod_rewrite can be removed from the ap­pli­ca­tion URL to make a “clean” web address available for the end users and search machine crawlers. De­vel­op­ers 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­troller classes, model classes, and view templates.

Con­troller classes

CodeIgnit­er gives de­vel­op­ers the op­por­tu­ni­ty to program in­di­vid­ual con­trollers as user defined classes. Web de­vel­op­ers create a separate PHP file for each con­troller in the index ap­pli­ca­tion/con­trollers/. Con­trollers contain the program logic of a web ap­pli­ca­tion developed with CodeIgnit­er and are created as sub­class­es of the CI_Con­troller 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­i­bil­i­ty public and protected functions from the parent class CI_Con­troller.

Note

The keywords public, protected, or private serve in PHP to define the vis­i­bil­i­ty 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­strict­ed 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­troller class has to contain a con­struc­tor function with which libraries, a data model, databases, or helper classes can be in­te­grat­ed. Since PHP5 __construct() has been used as the standard con­struc­tor 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­troller. The con­struc­tor function __construct() in­te­grates two helper classes, a database, and the data model News_model. The in­di­vid­ual code lines are excerpted in the source text.

Note

All con­troller classes that are defined for CodeIgnit­er 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­troller functions

If the basic framework for user defined con­trollers is located, the actual program logic follows in the form of con­troller functions with which views can be retrieved or in­ter­ac­tions with an in­te­grat­ed data model can be carried out.

In order for a con­troller to load a view, the un­der­ly­ing HTML document must be stored as a PHP file in the ap­pli­ca­tion/views/ index. A simple view for article pre­sen­ta­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­preter of the web server runs scripts instead of out­putting the PHP code as text.

To load a view in the con­troller, 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 program code reads as follows: first, CodeIgnit­er tests whether the index ap­pli­ca­tion/views/ contains a file with the name article.php. This inquiry is im­ple­ment­ed 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­re­spond­ing index, then if returns the value TRUE and CodeIgnit­er 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 CodeIgnit­er initiates the function $this->load->view(‘article’). This is used to load the cor­re­spond­ing file as a view into the ap­pli­ca­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­spec­tive file suffix is oblig­a­tory.

CodeIgnit­er is usually used as part of dynamic web ap­pli­ca­tions. These display dy­nam­i­cal­ly generated webpages to users instead of static HTML sites. This can be done by filling the view with data that matches the pa­ra­me­ters passed to CodeIgnit­er 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 specif­i­cal­ly 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 program, the above example needs to be sup­ple­ment­ed so that the data model embedded in the con­struc­tor 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­re­sponds 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­cia­tive array ($data). The data model News_model also delivers the data to the News con­troller, which passes it on to the view.

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

Model classes

Data models are used by CodeIgnit­er to provide functions that can be used to perform certain database op­er­a­tions. Exactly like con­troller 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­troller classes, all user defined model classes are sub­class­es of the parent class CI_Model. The in­her­i­tance is im­ple­ment­ed through the extends keyword. Model classes also in­cor­po­rate databases and other resources with the con­struc­tor function.

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

Model functions follow this basic structure, in which de­vel­op­ers define all database op­er­a­tions that should be available to the con­troller via the re­spec­tive data model.

Model functions

Model classes enable de­vel­op­ers to define in­di­vid­ual functions for database op­er­a­tions. In the above example, we utilized the user defined function get_data() in the con­troller 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­vel­op­ers can draw on the query builder class, which includes a set of pre­de­fined functions for classic database op­er­a­tions. An overview can be found in the official doc­u­men­ta­tion of CodeIgnit­er frame­works.

Routing with CodeIgnit­er

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

In the output con­fig­u­ra­tion of the $route array there are three default entries: the standard con­troller, 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­troller of the ap­pli­ca­tion. This is loaded by CodeIgnit­er whenever a URL other than the domain contains no further routing in­for­ma­tion. In the current example the routing rule defines the con­troller class home as the standard con­troller. Visitors who don’t specify the target webpage in the URL are therefore redi­rect­ed to home and presented with the welcome view. Usually this is a redi­rec­tion to the start page. If no con­troller is defined as the standard then CodeIgnit­er shows a 404-error page when the start page is called.

The second default entry in the $route array defines a con­troller that can be called when the con­troller addressed by the URL isn’t found in the ap­pli­ca­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­troller 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 au­to­mat­i­cal­ly 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 CodeIgnit­er: 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­pe­ri­ence this can have a negative influence on the ranking in search engines. As a rule web de­vel­op­ers 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­ter­na­tive 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­pli­ca­tion flow

The following graphic outlines the flow of an ap­pli­ca­tion on the basis of CodeIgnit­er in seven steps:

1. CodeIgnit­er uses index.php as a front con­troller for incoming HTTP requests. All basic resources needed to run the ap­pli­ca­tion are ini­tial­ized here.

2. As part of the routing, CodeIgnit­er checks which action is to be carried out. For this purpose, the ap­pli­ca­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­pli­ca­tion’s cache it’s delivered directly to the re­quest­ing web browser. Otherwise, the con­troller de­ter­mined during routing is executed with a preceding filter function.

4. The CodeIgnit­er framework contains an in­te­grat­ed filter that in­ter­cepts harmful inquiries. Before the ap­pli­ca­tion loads a con­troller matching the request, every HTTP request undergoes a security check.

5. If the request passes the filter, then the con­troller 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, CodeIgnit­er tem­porar­i­ly stops outgoing data to be able to directly answer repet­i­tive queries.

Benefits of the CodeIgnit­er framework

With more than 13,000 stars, CodeIgnit­er 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­pli­ca­tion are as follows:

Minimal con­fig­u­ra­tion effort: CodeIgnit­er is quick to get started. Users aren’t delayed for long with the con­fig­u­ra­tion of the framework and can instead begin with the de­vel­op­ment of the planned ap­pli­ca­tion almost im­me­di­ate­ly after the in­stal­la­tion. The con­fig­u­ra­tion effort is es­sen­tial­ly re­strict­ed to the settings in config.php and the ap­pli­ca­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 rec­om­mend­ed to create an .htaccess file to remove index.php from the path of ap­pli­ca­tion URLs via RewriteRule.  A database con­nec­tion con­fig­u­ra­tion is also necessary, which you enter into the database.php file.

  • Small footprint: CodeIgnit­er 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­men­ta­tion of the software. The minimal amount of code is due to the fact that the CodeIgnit­er basic system only contains a few small libraries. Ad­di­tion­al resources can be loaded as required.
  • Excellent per­for­mance: The lean core system means that CodeIgnit­er can score a higher speed in com­par­i­son 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 CodeIgnit­er “because it is faster, lighter, and the least like a framework.”
  • “Clean” URLs: CodeIgnit­er au­to­mat­i­cal­ly generates user friendly, search machine ap­pro­pri­ate URLs. Instead of accessing dynamic web content through query strings like other PHP frame­works, CodeIgnit­er uses a segment-based approach.

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

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

  • Free pro­gram­ming style: CodeIgnit­er is based on a free in­ter­pre­ta­tion of MVC ar­chi­tec­tur­al structure. There is no set pro­gram­ming style for de­vel­op­ers.
  • Extensive doc­u­men­ta­tion: CodeIgnit­er has a detailed doc­u­men­ta­tion in English, including a beginner’s tutorial in which the source code is clearly and well com­men­tat­ed. The CodeIgnit­er doc­u­men­ta­tion is on the project website as an online guide as well as an available version for download.
  • Community support: De­vel­op­ers who build their ap­pli­ca­tions on the basis of CodeIgnit­er can support them­selves with help from other users. The project is ac­com­pa­nied by an active community. A public forum can be found on https://forum.codeignit­er.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 CodeIgnit­er framework

Since the de­vel­op­ment of the CodeIgnit­er framework stagnated before the takeover by the BCIT took place, de­vel­op­ers searched for tech­no­log­i­cal im­prove­ments that had been adapted by com­pa­ra­ble frame­works in recent years but were un­suc­cess­ful with CodeIgnit­er.

  • 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­pli­ca­tions to store objects written in an object-oriented pro­gram­ming language such as PHP in a re­la­tion­al database. CodeIgnit­er doesn’t natively support ORM, so the technique can only be in­te­grat­ed through a third party.
  • No template engine: CodeIgnit­er 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­for­mance 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­a­ra­tion of the data gen­er­a­tion from the code for the pre­sen­ta­tion, which usually leads to a clearly struc­tured source code. If a template engine with slim syntax is used, this can sig­nif­i­cant­ly reduce the overall volume of the ap­pli­ca­tion code.
  • No name­spacing: With namespace, PHP allows you to separate code from different ap­pli­ca­tion groups. PHP de­vel­op­ers 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­te­grat­ed by a third party are common. CodeIgnit­er doesn’t use name­spacing anymore.
  • No PHP auto-loading: Since Version 5, PHP offers the functions __autoload() and spl_autoload_register() that allow required class de­f­i­n­i­tions to be loaded au­to­mat­i­cal­ly. The CodeIgnit­er framework doesn’t utilize this feature.
  • Fewer built-in libraries than other PHP frame­works: Because of the lean software design, CodeIgnit­er offers sig­nif­i­cant­ly fewer libraries in the output con­fig­u­ra­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­i­da­tion of form data, main­te­nance 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­vel­op­ers who are looking for a minimized framework can also interpret as an advantage.

CodeIgnit­er for the hurried reader

The table below provides an overview of the basic in­for­ma­tion of the CodeIgnit­er framework:

CodeIgnit­er  
Developer British Columbia Institute of Tech­nol­o­gy (BCIT)
Current release Version 3.1.2
Design pattern MVC/HMVC, Active Record, Chain of Re­spon­si­bil­i­ty
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­greSQL, MS SQL, SQLite, CUBRID, Interbase/Firebird, ODBC
ORM Only through third parties
Caching Yes
Template engine No
Name­spaces 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 CodeIgnit­er?

With its compact design and user-friendly syntax CodeIgnit­er is best suited for the prospec­tive pro­gram­mer. Anyone who has already had some ex­pe­ri­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­pe­ri­enced pro­gram­mers will also ap­pre­ci­ate the flex­i­bil­i­ty that allows them basic func­tion­al­i­ty with a reduced PHP framework. But if you want to use CodeIgnit­er, 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 CodeIgnit­er is equally suitable for small and large web projects.

Go to Main Menu