CodeIgniter is an open source web application framework for the PHP language. CodeIgniter has many features that make it stand out from the crowd. Unlike some other PHP frameworks you may have come across, the documentation is very thorough and complete—covering every aspect of the framework. CodeIgniter will also run in shared hosting environments as it has a very low footprint, yet it still has exceptional performance.
On the programming side, CodeIgniter is both PHP4 and PHP5 compatible, so it will run on the majority of web hosts out there. It also uses the Model View Controller (MVC) design pattern, which is a way to organize your application into three different parts: models—the database abstraction layer, views—the front end template files, and controllers—the business logic of your applications. In the core, CodeIgniter also makes extensive use of the Singleton design pattern. This is a way to load classes so that if they are called multiple times, the same instance of the class will be returned. This is highly useful for database connections, as you would only want one connection each time that the class is used.
CodeIgniter also has an implementation of the Active Record pattern. This makes it easy to write complex SQL queries and makes your application more readable. Active Record also allows you to easily swap and change database drivers. This allows you to write the queries in PHP and still use a MySQL backend, and also gives you the option to switch to an Oracle database –without having to rewrite the queries in your application.
CodeIgniter also comes with a number of highly useful libraries and other sets of functions that help you to build your applications. This leaves you to focus on the small part of your application that is unique, rather than the part that is used across all projects, such as database queries and parsing data.
In this chapter, we will:
Install CodeIgniter
Learn about the MVC Design Pattern
Learn how to format your code according to the CodeIgniter PHP Style Guide
Learn how CodeIgniter URLs work
Learn about CodeIgniter-specific files
Users on older versions of CodeIgniter should upgrade to the latest version for a number of reasons.
Firstly, each new release comes with many bug fixes, and more importantly, security patches. This makes applications running on older versions of CodeIgniter more vulnerable to attack than the newer versions.
There are also more features. For example, a new Cart Library was introduced in CodeIgniter 1.7, allowing users to build a simple shopping cart application easily, using a native supported library rather than a third-party one.
To upgrade to CodeIgniter 1.7, follow the instructions given next and simply migrate your application folder over to the newer codebase.
This book assumes prior knowledge of PHP—this should also stretch to a web server. CodeIgniter needs a web server to run on, just like any other PHP application. You can install CodeIgniter locally just for testing, or use it on your current web server; anywhere will suffice.
The first step to getting started with CodeIgniter is to download the files from the website. The website is located at www.codeigniter.com. This website includes a backlog of all of the previous versions of CodeIgniter, as well as a Subversion Repository (SVN) for the latest version. In our case, we can simply download the latest version straight from the home page—currently 1.7.2— by clicking on the Download CodeIgniter button, as seen in the next screenshot.
When you have downloaded the ZIP file, unzip it using your favourite file archiving program. You will now have a folder named CodeIgniter_1.7.2
. The folder should contain two files and two directories, as seen in the next screenshot.
The system
directory holds the core CodeIgniter files, libraries, and other CI specific stuff, such as the logs and cache directories. It also houses the application
folder—this is the only folder you truly need to worry about, as this is the only place where you need to put your files. As you can guess, this is the folder where all your application-specific code goes, and includes the configuration files that you may need to edit.
Simply open this folder in your code editor of choice and we'll go ahead and install CodeIgniter in our final step. We need to edit the base URL—the URL at which you will you access your application—and to do this we need to open the file /system/application/config/config.php.
The value that we need to change is the array item $config['base_url']
which is currently set to http://example.com/
—simply change this to your URL.
When that is done, navigate to your base URL and you should see the CodeIgniter welcome screen, as seen in the next screenshot.
Although you have heard this term mentioned in this book already, you may not know what the term means. In short, Model View Controller—from now on, referred to as MVC—is a software development design pattern. MVC is an approach to separating your applications into three segments: Models, Views, and Controllers. MVC structures your application in this way in order to promote the reuse of program code.
The Model represents any type of data that your application may use. Some examples of data that your application might use would be: a database, RSS Feeds, API calls, and any other action that involves retrieving, returning, updating, and removing data.
Views are the information that is being presented on the screen to users through their web browsers. These are usually HTML files, sometimes containing PHP code that builds the template for the website. In CodeIgniter however, views can be page segments, partial templates, or any other type of page or template.
Finally, Controllers are the business logic of your application. They serve as an intermediary between Models and Views. The Controller will respond to HTTP requests and generate web pages.
However, CodeIgniter's approach to MVC is very loose. This means that Models are not required. This is for a number of reasons. Firstly, CodeIgniter's Database Library can be used in both Models and Controllers—meaning that the extra separation of Models can be bypassed. Secondly, the Model isn't tied to the database, as it is in other frameworks such as Ruby on Rails, so the Model isn't needed in this regard. Finally, if using a Model in your application will cause unnecessary complexity, then the Model can simply be ignored.
However, Models are extremely useful, even though they are optional. Models can be loaded from any Controller, so if you use a Model function in multiple controllers and you need to change the function, you only need to edit it in one place rather than in all of the controllers. Complex queries should really be put into a Model. A collection of related queries should also be put into a Model as they can be grouped together. This makes your applications simpler, and it allows you to use the functions in any Controller.
Controllers are the core of your application because they determine how HTTP requests should be handled. Let's dive right in and create a simple Hello World controller. Create a file called helloworld.php
in system/application/controllers/
.
<?php class Helloworld extends Controller { function HelloWorld() { parent::Controller(); } function index() { echo("Hello, World!"); } } ?>
Let's dissect this controller to get a better understanding of controllers.
Firstly, you can see that the controller is a class that extends the base Controller class. The next thing to note is that there is a function with the name index
. This is the default function, and will be called when another function has not been called. To see this being run, simply navigate to the URL http://yourwebsite.ext/index.php/helloworld/
and you should see the words Hello, World! on the screen.
All Controller class names should start with an uppercase letter, and the rest of the name should be lowercase. Controllers should always extend the base class so that you can use all of CodeIgniter's syntax and have access to all CI resources.
If you have a constructor in your Controller then you need to call upon the Controller
constructor, as we have in the example HelloWorld Controller. You should call it as follows:
Parent::Controller();
CodeIgniter has the ability to set a Controller as the default controller. This is the controller that is to be called when no other controller is passed to index.php
. A default CodeIgniter install will set the default controller to welcome_message.php
– this is the default CI welcome page, as shown earlier.
To set a different default controller, open the file system/application/config/routes.php
and change welcome
to the name of any other controller in your application.
$route['default_controller'] = "welcome";
You can remap function calls by using a function in your controller called _remap()
—this will be called every time that the controller is called, even if a different function is used. This is useful for developers who wish to easily remap their function calls in order to provide a different Uniform
Resource Identifier (URI) structure, or to remap functions instead of extending CodeIgniter's routing class.
The function string will be passed to the function. You would usually have a function that looks like this:
Function _remap($method) { if($method == "method_name") { $this->$method(); } else { $this->default_method(); } }
Now that you know what a Model is and what it's used for, we can take a look at how to construct a Model.
Models are stored in system/application/models/
. The class of your model should have the first letter capitalized and the rest of the name lowercase, and also extend the base class of Model. The class should also have a constructor that calls upon the base class constructor, as seen in the next code example.
<?php class Mymodel extends Model { funcion Mymodel() { parent::Model(); } } ?>
The filename of this model should be an all-lowercase version of the name; the filename therefore will be mymodel.php
.
A model is loaded from Controller functions. Loading a model takes just one line of code.
$this->load->model('model_name');
In this instance, you should replace model_name
with the name of your model. If your model is located in a sub-folder, you would load the model as follows:
$this->load->model('sub_folder/model_name');
Once loaded, you access your model functions by using the global object with the same name as your model name.
$this->model_name->function_name();
You can assign a new name for your Model object by passing it to the second parameter of the loading function.
$this->load->model('model_name', 'different_name');
Now you would call your model functions as follows:
$this->different_name->function_name();
Here's an example of a controller calling a model and serving a view.
<?php class Shop extends Controller { function Shop() { parent::Controller(); } function index() { $this->load->model('products'); $products = $this->products->build_list(); $this->load->view('shop', $products); } } ?>
When a model is loaded, it does not connect to the database automatically unless you autoload the database class for your application. You can tell the model to connect to the database automatically by passing boolean TRUE
as the third parameter.
$this->load->model('model_name', '', TRUE);
The model will now connect to the database using the setting defined in your database.php
configuration file, which is located in system/application/config/
.
You can pass an array of configuration details to the third parameter if you wish to use a database other than the one that's set up in your database configuration file.
$config['hostname'] = "localhost"; $config['username'] = "myusername"; $config['password'] = "mypassword"; $config['database'] = "mydatabase"; $config['dbdriver'] = "mysql"; $config['dbprefix'] = ""; $config['pconnect'] = FALSE; $config['db_debug'] = TRUE; $this->load->model('model_name', '', $config);
Views are your template files. They are what is output to the browser, and should be mostly HTML code, with some PHP code. Put simply, views are HTML files of your template; they can also be page segments, such as a header or footer. View files can also call other views, if you need such flexibility.
Views are located in the system/application/views/
folder, and can be stored in subfolders inside this main views
folder.
Loading a view is done in the same way as loading a model; it takes just one line of code.
$this->load->view('view_name');
Here, view_name
would be the name of the view file that you wish to load. You can also pass an array of data to a view file by passing an array as the second parameter of the load->view
function.
$data['title'] = "My Web Page"; $this->load->view('view_name', $data);
You would then be able to use the variable $title
in your view file to echo out the page title.
You load multiple views in the same way as you load just one view. CodeIgniter intelligently handles multiple calls to $this->load->view
, and will append these calls together. Here is an example:
function index() { $data['title'] = "My Web Page"; $this->load->view('header', $data); $this->load->view('navigation'); $this->load->view('content'); $this->load->view('footer'); }
Adding data to a view file is a very simple process, which we have touched upon already. You pass data to a view file by using the second parameter of the load->view
function. All view data must be passed as an array or an object. This is because CI runs this array or object through PHP's extract function, which simply takes an object or array key and creates a variable for it with the same name. Let's look at an example:
$data = array( 'title' => "My Web Page", 'heading' => "Welcome to my web page", 'content' => "This is my first web page using Codeigniter!" ); $this->load->view('main', $data);
You will then be able to use this data in your view, as illustrated below:
Creating loops in view files has been a stumbling block for a few developers. By passing a multidimensional array to a view file, you can easily establish a loop in any of your view files. Let's take a look at an example.
<?php class Todo extends Controller { function index() { $data['todo_list'] = array("buy food", "clean up", "mow lawn"); $this->load->view('todo', $data); } } ?>
This is a very simple Controller. Your view file for this would be as follows:
You are also able to return view files as data; this can be useful if you wish to process this data in some way. Simply set the third parameter to boolean TRUE
—and it will return the view data.
$this->load->view('welcome', NULL, TRUE);
CodeIgniter uses an output buffer to take all calls to the load view function, and processes them all at once, sending the whole page to the browser at the same time. So when you return views as data, you will be able to save the contents of the view inside a variable for whatever use you need.
CodeIgniter comes with built-in functionality that enables you to load libraries, plugins, helpers, models, and so on, on each request. This is useful for database intensive applications, as you can autoload the Database Library so that you won't need to load it yourself.
Simply open up the application/config/autoload.php
file and put the name of the library or other type of file that you want to autoload into the appropriate array.
CodeIgniter does not force any specific coding style on you as a developer. However there is a PHP Style Guide that sets a number of rules that you can use when developing for CodeIgniter. These are mostly style rules to help your code fit in with the core code better, as the core development team follows these rules, as well as those of us who develop using the framework. I will not go over the entire style guide, but I will highlight the most noteworthy conventions.
The
PHP closing tag ?>
is optional to the PHP parser. If used, any whitespace after the PHP closing tag can result in PHP errors, warnings, or even blank pages. For this reason, all PHP files should omit the closing PHP tag, and instead use a comment block to display relevant details for the file location. This allows you to signify that a file is complete.
<?php class Helloworld extends Controller { function index() { echo("Hello, World!"); } } ?>
As we have touched upon before, class names should always have their first letter in uppercase and the rest of the name in lowercase. Multiple words should be separated with an underscore and not use the CamelCase convention.
class My_class
The class and constructor method should have identical names. Take this example:
class My_class { function My_class() { } }
Here is a set of examples of improper and proper method naming, taken directly from the PHP Style Guide of the CodeIgniter user guide.
function fileproperties() // not descriptive and needs underscore separator function fileProperties() // not descriptive and uses CamelCase function getfileproperties() // Better! But still missing underscore separator function getFileProperties() // uses CamelCase function get_the_file_properties_from_the_file() // wordy
The guidelines for variable names are very similar to those for class and method names. Variable names should only contain lowercase letters, should use underscore separators to separate words and not use CamelCasing, and should be named to indicate their contents.
$f = 'foo'; // single letter variable name, does not explicitly show what it contains $Text // contains uppercase letters $someTextHere // uses camelCase and does not show it's contents $userid // multiple words, needs an underscore to separate them
CodeIgniter recommends that you comment your code as much as possible. This is for two reasons: it helps inexperienced programmers who may be working on the same project as you, or if you release your code; and it will help you months down the line to understand the code more quickly than if there were no comments. There isn't a particular required commenting style, but CodeIgniter recommends that you use DocBlock styling. This is recommended as it will be picked up by many Integrated Development Environments (IDE).
/** * Class Name * * @package Package name * @subpackage Subpackage Name * @category category name * @author Author Name * @linkhttp://example.com */
When commenting your code, you should use singe line comments and leave a line between a large comment block and the code. I would personally recommend that comments mean something.
When using the keywords TRUE, FALSE, and NULL in your applications, you should always write them in uppercase letters.
CodeIgniter URLs use Uniform Resource Identifiers (URI). In simple terms, CodeIgniter's URLs are simply segments. These segments are then split up and used to load a particular controller and method. Here is a typical CodeIgniter URL:
Everything after the index.php
segment is used by CodeIgniter to determine what to load. The first segment is the name of the Controller. The second segment is used to determine which function to load—if this is blank then the index function will be used.
The final segment will be used to pass any data to the function.
You can remove the index.php
part of the URL by adding a .htaccess
file to the root of your CodeIgniter install. Here is an example file:
RewriteEngine on RewriteCond $1 !^(index\.php|images|robots\.txt) RewriteRule ^(.*)$ /index.php/$1 [L]
This will redirect anything to the index.php
file except for index.php
, the images
folder, and robots.txt
. You can add any other items to the list as you so wish, such as a folder for .css
files or even JavaScript files.
CodeIgniter has a number of different file types that can be used in your applications to make your job easier. These are helpers, plugins, and libraries. They all differ in some way, with their own unique abilities.
Helper files are a collection of functions in a particular group. For example, CodeIgniter has a URL helper, which lets you easily print your website URL or the current URL, build links, and a few other functions too. Helpers can be used within Models, Controllers, and View files.
Helpers are not written in an object oriented format in the way that Controllers and Models are, they are simply a collection of procedural functions.
Loading a helper is just like loading anything else in CodeIgniter; it takes just one line of code.
$this->load->helper('form');
Because helper files are procedural files, you simply use the function in the same way as you call a standard PHP function, and not in the objective format as you would with models.
For example, to echo your site URL using the URL helper, you would use:
<?php echo base_url(); ?>
Even though helpers are procedural files, you can extend them in a literal sense. To do this, create a file in the system/application/helpers/
folder, with the same name as a core CI helper with the prefix MY_
. You can change this prefix, but we won't go into that right now.
Then you simply create a function inside this file with the same name as the function that you wish to replace, or add a new function.
For example, if you wanted to extend the Form Helper
, you would create a file called MY_form_helper.php
inside the system/application/helpers/
folder, and create any functions that you wish to add.
Plugins work in almost exactly the same way as Helpers. The main difference is that a plugin should be used to add a single function, instead of a collection of functions. Helpers are also considered to be part of the core framework, whereas plugins are intended to be created and shared by the community. Plugins are stored inside the system/application/plugins/
folder.
Loading a plugin is almost the same as loading a helper. The only difference is the function used.
$this->load->plugin('name');
Where name
is the name of the plugin you wish to load.
Libraries provide extra functionality that can be used across multiple projects. Libraries usually abstract functions for many different tasks. For example, the Database Library provides a way to create SQL functions in very simple, readable ways. It is advisable to keep Library calls out of your View files, and a helper should be used to perform the operation instead.
You can easily create your own libraries. The first step in creating a library is to create a file inside the system/application/libraries/
folder, with a relevant name; you should also take the naming conventions outlined in the style guide into account.
The next step is to create a class inside this file, with the same name as your PHP file—but without the .php
extension. You do not need to extend any classes when creating your own library.
When using CodeIgniter, you load helpers, libraries, and other resources by using the super object $this->. However, when creating your own library, you will not have access to this unless you explicitly add it in by using the following function:
$CI =& get_instance();
Once you do this inside a function, you would use $CI in place of $this when utilizing CodeIgniter resources.
To extend a core CodeIgniter library, first create a file with the same name as the library you wish to extend, but add the MY_
prefix. For example, to extend the Session
class, create a file called MY_Session.php
and place it inside the system/application/libraries
folder. Once this is done, you simply extend the core library as follows:
Replacing core libraries is similar to extending them. Instead of using the MY_
prefix in your file name and class name, you drop the prefix for the filename and use the prefix CI_
for the class name. This is because all CodeIgniter core libraries have the prefix CI_
. Staying with the session class, we would replace it as follows:
<?php class CI_Session { } ?>
To load the library, you would do so as if you hadn't changed anything:
$this->load->library('session');