Introduction

Codeigniter is a lightweight PHP Framework that implements the model-view-controller pattern (MVC). This tutorial covers some selected aspects that help to get started with codeigniter. A few minutes of reading can save a few hours of try-and-error.

1. Controller Constructor

The controller classes are located in system\application\controllers. It's important that all controller class always extend the controller interface provided by the framework and that the constructor calls the parent class constructor:

  1. class My_first_controller extends Controller {
  2. function My_first_controller(){
  3. parent::Controller(); // <- don't forget this
  4. // here goes your code
  5. {
  6. }

2. URL Parameter In Functions

Codeigniter uses an interesting approach to generate speaking URLs. The URLs are constructed as follows:

.../My_first_controller/hello/world/en

This URL would call a function named hello in the controller class named My_first_controller and passes two parameters to the function: world and en. Making use of this could look like this:

  1. class My_first_controller extends Controller {
  2. function hello( $who, $lang ){
  3. if ( $lang = "en" ){ echo( "Hello $who!" ); }
  4. if ( $lang = "de" ){ echo( "Hallo $who!" ); }
  5. }
  6. }

The output would then be “Hello world!”. BUT of course one should never use echo in a controller.

3. Fetch Post Parameters

Reading post parameters with naked PHP would look something like this:

  1. $user = isset( $_POST["user"] ) ? $_POST["user"] : "";

This rather inconvenient way of reading post parameters is abstracted by the Codeigniter framework:

  1. $user = $this->input->post( "user" );

Additionally using a XSS filter on your post inputs can be done as easy as this:

  1. $user = $this->input->post( "user", true );

More information about reading parameters: 

www.codeigniter.com/user_guide/libraries/input.html

4. Using Config Files

Config files are always located in system\application\config. In this folder one can also find the default config file with basic global variables: config.php. Accessing a variable in this config file within the controller works like this:

  1. $this->config->item( "base_url" );

Sooner or later every project will require own config files to store global variables. Codeigniter allows to create custom config files in the config folder (in this case custom.php). In such a config file new values can be stored in the config array:

  1. $config['version'] = "0.1.4";

To use the configurations the config file needs to be loaded somewehre within a controller class:

  1. $this->config->load('custom');

The version number that is stored in the configuration file can be accessed like this:

  1. $this->config->item('version');

More information about conifg files:

codeigniter.com/user_guide/libraries/config.html

5. Base URL

In every projekt one of the frist things to do is to set the base url in the default config file (system\application\config\config.php).

  1. $config['base_url'] = "http://www.mydomain.tdl";

Everytime when the project folder is moved to a different location this configuration needs to be adjusted. The following snippet generates the base_url value and can be used instead of a static domain string:

  1. $config['base_url'] = "http://".$_SERVER['HTTP_HOST'] .
  2. preg_replace('@/+$@','',
  3. dirname($_SERVER['SCRIPT_NAME'])).'/';

6. Writing own Libraries

Another folder in the framework is dedicated to libraries (system\application\libraries). These libraries are classes that have general functionallity. The file that contains a library needs to be named after the class that it contains: Myfirstlib.php would have to contain a class named Myfirstlib. Note that file names and class names have to be capitalized. To include a custom library in a controller class just one line of code is necessary:

  1. $this->load->library('myfirstlib');

Note that this already creates an instance of the library class! The instance can be used right away:

  1. $this->myfirstlib->helloworld();

More on how to create custom libraries:

www.codeigniter.com/user_guide/general/creating_libraries.html

7. Form Helper

In the view classes the finial HTML has to be generated (system\application\views). This is the V in MVC. Codeigniter provides so called helper classes for this. The form helper class, for instance, contains methods to abstract the generation of HTML form elements. This helper class can be loaded in the constructor of a controller class like this:

  1. $this->load->helper('form');

That's it! Now a HTML form (e.g. to subscribe for spam) can be created by using the helper methods:

  1. echo form_open("spamsubscription/index");
  2. echo form_input( array( "name" =>
  3. "email", "value" => "", "size" => "30" ) );
  4. echo form_submit("submit", "Sign me up for spam!");
  5. echo form_close();

8. Header Library

The Header Library 2.0 is a useful third party library that offers functionallity that is not included in codeigniter (Header Library v2.0). This library helps to create the HTML header (i.e. what is framed in <head></head> in an HTML document). It offers convenient functions to add stylesheets, JavaScript, meta tags and more. After the library is downloaded and placed in the library folder it can be included like this:

  1. $this->load->library('header');

Use the generated tags in your view files:

  1. <?php echo $header["doctype"] ?>
  2. <html>
  3. <head>
  4. <title><?php echo( $pageTitle ); ?></title>
  5. <?php
  6. echo $header["stylesheets"];
  7. echo $header["javascript"];
  8. ?>
  9. </head>

9. Multiple Forms on one Page

When using multiple forms on one page the following routing approach can be used to ensure a clear concept in the controller classes:

  1. class My_first_controller extends Controller {
  2.  
  3. public function index(){
  4. if ( $this->input->post("submit_button_1") ){
  5. $this->form1();
  6. }
  7. if ( $this->input->post("submit_button_2") ){
  8. $this->form2();
  9. }
  10. }
  11.  
  12. private function form1(){
  13. // react on form1 inputs here
  14. }
  15.  
  16. private function form2(){
  17. // react on form2 inputs here
  18. }
  19. }

Note that every form should target to your index function. From the index function, depending on the name of the submit button that was used, the code execution will be routed to a private function that can not be executed from the URL.

10. Static Helper Functions

Finally it is often useful to have some static helper functions that you can call anywhere without worrying about creating an instance of an object.

  1. class Utilities{
  2.  
  3. public static function versionStr( $version ){
  4. return( "Version: $version" );
  5. }
  6.  
  7. public static function getLogDateTime(){
  8. return( date("Y/m/d H:i:s") );
  9. }
  10.  
  11. }

These static functions can be called like this:

  1. $log .= Utilities::getLogDateTime() . "something happened";
social bookmark now:facebook.comdel.icio.usdigg.comgoogle.comlive.comMister WongTechnorati