Home Web-development CodeIgniter 1.7 Professional Development

CodeIgniter 1.7 Professional Development

By Adam Griffiths
books-svg-icon Book
Subscription
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
Subscription
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started with CodeIgniter
About this book

CodeIgniter is an open source PHP framework with a small footprint and exceptional performance. It gives you a rich set of libraries for common tasks, with a simple interface to access them. There are several unexplored aspects of CodeIgniter that can help developers build applications more easily and quickly. In this book, you will learn the intricacies of the framework and explore some of its hidden gems.

If you want to get the most out of CodeIgniter, this book is for you. It teaches you what you need to know to use CodeIgniter on a daily basis. You will create mini-applications that teach a specific technique and let you build on top of the base.

This book will take you through developing applications with CodeIgniter. You will learn how to make your CodeIgniter application more secure than a default installation, how to build large-scale applications and web services, how to release code to the community, and much more. You will be able to authenticate users, validate forms, and also build libraries to complete different tasks and functions.

The book starts off introducing the framework and how to install it on your web server or a local machine. You are introduced to the Model-View-Controller design pattern and how it will affect your development. Some important parts of the CodeIgniter Style Guide are included to keep CodeIgniter development as standardized as possible; this helps greatly when working as part of a team or taking on an old CodeIgniter project. You will quickly move on to how CodeIgniter URLs work and learn about CodeIgniter-specific files such as helpers and plugins. By the time you finish this book, you will be able to create a CodeIgniter application of any size with confidence, ease, and speed.

Publication date:
April 2010
Publisher
Packt
Pages
300
ISBN
9781849510905

 

Chapter 1. Getting Started with CodeIgniter

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

 

Upgrading from older versions of CodeIgniter


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.

 

Downloading and installing CodeIgniter


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.

Getting the CodeIgniter files

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.

Tip

The base URL value needs to have a trailing slash (a forward slash) at the end.

When that is done, navigate to your base URL and you should see the CodeIgniter welcome screen, as seen in the next screenshot.

 

Introducing Model View Controller (MVC)


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: The business logic


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();

Defining a default 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";

Remapping function calls

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();
  }
}
 

Models: Data abstraction layer


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.

Loading a Model

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);
  }
}
?>

Connecting to your database automatically

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: Your template files


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

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.

Loading multiple views

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 dynamic data

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:

<html>
<head>
  <title><?php echo $title; ?></title>
</head>
<body>
<h1><?php echo $heading; ?></h1>
<?php echo $content; ?>
</body>
</html>

Creating loops

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:

<html>
<head>
  <title><?php echo $title; ?></title>
</head>
<body>
<h1><?php echo $heading; ?></h1>
<?php echo $content;?>
<h2>My Todo List</h2>
<?php
foreach($todo_list as $item)
{
  echo $item;
}
?>
</body>
</html>

Returning views as data

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.

 

Autoloading resources


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.

 

Formatting your code—PHP Style Guide


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.

PHP closing tag

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.

Incorrect

<?php
  class Helloworld extends Controller
  {
    function index()
    {
      echo("Hello, World!");
    }
  }
?>

Correct

<?php
  class Helloworld extends Controller
  {
    function index()
    {
      echo("Hello, World!");
    }
  }

/* End of file helloworld.php */
/* Location: system/application/controllers/ */

Class and method naming

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.

Incorrect

class myClass
class MYClass

Correct

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.

Incorrect

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

Correct

function get_file_properties() // descriptive, underscore separator, and all lowercase letters

Variable names

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.

Incorrect

$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

Correct

for ($i = 0; $i <= 10; $i++)
$text
$user_id

Commenting

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.

Poor

// a foreach loop

foreach($posts as $post)
{
  echo $post;
}

Good

// loop through the blog posts and echo each out

foreach($posts as $post)
{
  echo $post;
}

This is my personal recommendation, because silly comments such as the first won't help you a few months down the line, simply because you can already tell it's a Foreach loop.

Use of TRUE, FALSE, and NULL

When using the keywords TRUE, FALSE, and NULL in your applications, you should always write them in uppercase letters.

Incorrect

if($active == true)
$zero = null;
function test($test = false)

Correct

if($active == TRUE)
$zero = NULL;
function test($test = FALSE)

Short opening tags

You should always use full PHP opening tags and not short tags, just in case a server does not have short_open_tag enabled. CodeIgniter can rewrite short tags, although the PHP Style Guide states that full opening tags should be used.

Incorrect

<? echo $foo; ?>
<?=$foo?>

Correct

<?php echo $foo; ?>

One statement per line

You should always have one statement per line in CodeIgniter applications. This improves code readability, and will also makes things easier to find.

Incorrect

$foo = 'bar'; $bar = 'foo'; $baz = 'zip';

Correct

$foo = 'bar';
$bar = 'foo';
$baz = 'zip';

 

CodeIgniter URLs


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.

Removing the index.php file

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.

Adding a URL Suffix

You can specify in your system/application/config/config.php file to add a suffix to your URLs. Take this example:

http://mywebxite.ext/products/books/

You can add a suffix so that the URL becomes:

http://mywebsite.ext/products/books.html

You don't have to use .html, I just used it as an example.

 

CodeIgniter specific 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.

Helpers

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

Loading a helper is just like loading anything else in CodeIgniter; it takes just one line of code.

$this->load->helper('form');
Loading multiple helpers

You can load multiple helpers by passing an array of values to the first parameter.

$this->load->helper( array('form', 'url', 'cookie') );

Using a helper

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(); ?>

"Extending" Helpers

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

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

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.

Loading multiple plugins

To load more than one plugin, simply pass an array to the load function.

$this->load->plugin( array('name1', 'name2', 'name3') );

Using a plugin

Once a plugin is loaded, you simply call it in the same way as you would call a standard PHP function.

Libraries

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.

Creating your own libraries

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.

Using CodeIgniter resources within your 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.

Using your class

To load your library, you simply use the following function:

$this->load->library('name');

Where name is the name of the library you wish to load.

Extending core libraries

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:

<?php
  class MY_Session extends CI_Session
{
    function MY_Session()
    {
      parent::CI_Session();
    }
}
?>
Loading your extended library

You load your extended library in exactly the same way as you load the core library. In our example, we'd use the following line of code. Note that I do not include the MY_ prefix.

$this->load->library('session');

Replacing core libraries

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');
 

Summary


Well done. You've made it through Chapter 1. That's all you need to know to get started with CodeIgniter. In Chapter 2, Learning the Libraries, we'll go over some of the great libraries that CodeIgniter comes with, taking you to a higher level of knowledge.

About the Author
  • Adam Griffiths

    Adam Griffiths is a student and freelance CodeIgniter Developer based in the United Kingdom. He has five years web development experience, the last two being largely influenced by CodeIgniter. He has worked on many websites, both large and small, from small blogs to large multi-national companies. He is well versed in development techniques and how to squeeze that little bit more from an application. He has also made a number of contributions to the CodeIgniter Community, most notably The Authentication Library, a very simple-to-use but full-featured Authentication Library for CodeIgniter.

    When CodeIgniter and PHP aren't spiralling around his head, Adam enjoys practising card and mentalist tricks, mainly sleight of hand and card handling. He has performed at local and formal functions for hundreds of people. He is also a guitar player and enjoys playing acoustically at pubs and small gigs. Moving back towards computing, he has a deep interest in Cryptography. He loves finding patterns in data and loves using pen and paper to decipher any cipher text he may find around the web.

    Browse publications by this author
CodeIgniter 1.7 Professional Development
Unlock this book and the full library FREE for 7 days
Start now