Programming with CodeIgniter MVC

3.5 (2 reviews total)
By Eli Orr , Yehuda Zadik
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Getting Started

About this book

The CodeIgniter Model-View-Controller framework provides genius simplicity, flexibility, and efficient resource usage, boosting performance and reusability.

"Programming with CodeIgniter MVC" reviews the unique features of CodeIgniter using simple, easy-to-follow, and practical examples.

Programming with CodeIgniter MVC provides a simple step-by-step guide to efficiently utilizingthe CodeIgniter MVC framework for developing web applications. This book is packed with engaging examples to understand the usage of controllers, libraries, and (Codeigniter) CI Models. This book commences with a quick discussion of the CodeIgniter Integration with  external plugins such as Flickr API, Google Maps and more will be reviewed with clear usage examples. It will then cover CI naming convention rules, mandatory and optional configurations, and usage within a CI project. It will also cover user defined configurations.

By the end of this book, you will not only understand user-defined libraries in a CI framework, but also their services, role, usage, and scope with the help of an example-based approach. The book also covers helpers, models, and views, as well as their usage.

Using this book, youwill soonbe able to develop feature-rich web applications using the CodeIgniter MVC framework. "Programming with CodeIgniter MVC" is a one-stop solution to developing solutions with CodeIgniter MVC.

Publication date:
September 2013
Publisher
Packt
Pages
124
ISBN
9781849694704

 

Chapter 1. Getting Started

This chapter covers the basics of the CI development framework and its usage by reviewing some fundamental web application examples. We will start with a basic hello world example and move to an interactive contact-form integration with a database. We will construct the CI applications by following a step-by-step method. Throughout this chapter, we need to remember that the CI development framework is an MVC-based development architecture (for more information, refer to the Wikipedia definition at http://en.wikipedia.org/wiki/Model-view-controller).

This chapter will primarily focus on the following topics:

  • The CI project directory tree framework

  • Configurations (routing and autoloading are covered in this chapter, while the other issues are covered in Chapter 2, Configurations and Naming Conventions)

  • Example 1: hello world

  • Example 2: passing parameters to a view

  • Example 3: the database query by a model rendering results to a view

  • Example 4: interactive contact forms

By reviewing these examples, we will get the basics of using CI resources. We will begin by briefly reviewing the CI resources used. Then we will review a web application code that loads a static view page. Next we will use the model to retrieve data from a database and show it in a view. Finally, we'll add a view with a contact form to enter input and save it by calling a controller method into the database.

 

Installing CodeIgniter


First of all, we need to have a hosted PHP server (Version 5.3 or later) and a MySQL (one of the latest versions) server, where we know the database credentials. Local database access from the PHP is recommended for simplicity.

Note that the server will operate in a CGI (Common Gateway Interface) fashion in order to let CI operate. We can have a local web development environment on our PC or a remote server hosted and dedicated.

Once we've set up a local web development environment, we'll need to download the latest version of CI, which is Version 2.1.2 at the time of writing this book. The link to download the latest version is http://codeigniter.com/downloads/. Now, if we look inside the CI folder, we should see the following directory tree:

codeigniter/
  index.php
  application/
  cache/
  config/
  controllers/
  core/
  errors/
  helpers/
  hooks/
  language/
  libraries/
  logs/
  models/
  third_party/
  views/
  system/
  core/
  database/
  fonts/
  helpers/
  language/
  libraries/
 

Folders overview


The root folder contains the index.php file, which handles all the URI requests. The index.php file will process them with the CI core, and apply our application controllers using the models, libraries, and helpers loaded by the controllers and rendered views, license.txt, which is the CI's license file. .htaccess is used for configuring the CI routing and removing index.php from the URL. JavaScript, CSS, and HTML is incorporated into the rendered PHP output and their usage is elaborated in Chapter 7, Views.

Let's review the folders and their content application.

The application directory folder is the root directory of our main activity project coding zone. This is the heart of the CI-developed application project.

Mandatory components

Let's take a look at the mandatory components.

  • application/config: This folder contains all the CI application configuration files, which are covered in Chapter 2, Configurations and Naming Conventions.

  • application/controllers: This folder contains all the application controllers in the CI application project. A controller, as mentioned in the Preface, is a component in the MVC-design architecture that handles the request by the user and presents the data shown to the user. A controller in CI is a class extending a base class of the CI controller. The class methods can be executed or called with a proper URI. The naming conventions related to the controller definition and usage will be covered in Chapter 2, Configurations and Naming Conventions.

  • application/views: This folder contains all the view files. A view is the HTML content executed by the user browser that presents and interacts with the user. A view can be a webpage or an RSS page.

The following components are not mandatory but are highly recommended:

  • application/models: This folder contains all the project model files. A model is the component of the MVC design architecture, which handles the data stored in the database. A model in CI is a PHP class that is designed to work with the information in the database. Chapter 6, Models, will elaborate on the CI models concept, definition, and usage with several usage examples.

  • application/helpers: This folder contains all the additional helper files to the CI helpers. They can be third-party or created by the developer. A helper file is a collection of independent procedural functions in a particular category. Each helper function performs one specific task, with no dependence on other functions. Chapter 5, Helpers, will elaborate on the CI helpers concept, definition, and usage with several usage examples.

  • application/libraries: This folder contains all the libraries of the CI application project created by the developer. A CI library is technically a PHP class. The scope of the library can be any project resource, such as helpers, models, controllers, and views. For example, a library can provide Facebook library API services to simplify the application code for Facebook integration. Chapter 4, Libraries, will elaborate on the CI libraries concept, definition, and usage with several usage examples.

  • system: This is the root of the CodeIgniter core directory. The system folder contains important system components in the subfolders, such as core, database, helpers (built-in system helpers), and libraries (built-in system libraries).

    Tip

    Do not edit any of these files! Upgrading is much easier if we don't.

 

Example 1 – hello world


Initially, we will start with a simple example that displays Hello World on the rendered web page. This is an example that doesn't use a database.

The URI will be http://ourdomain.com/index.php/hello.

We can eliminate the index.php file from the path to enable a shorter URI; that is, http://ourdomain.com/index.php/hello.

In order to enable these shorter URIs, we will make configuration changes as described in Chapter 2, Configurations and Naming Conventions, regarding the config.php index_page setting in config.php.

We will build the following two scripts:

  • Controller class: application/controllers/hello.php

  • View script: application/views/helloview.php

In this example, we use the default configuration. For more information about configurations, refer to Chapter 2, Configurations and Naming Conventions. The controller in this example passes the parameters that are displayed in the view.

Tip

Passing the parameters from the controller to the view is optional.

The controller file

Here's the code sample of the controller. The controller is responsible for rendering the view with the parameters, such as mega title and message. For naming the controller classes, refer to Chapter 2, Configurations and Naming Conventions.

<?php 
class Hello extends CI_Controller {
  * Index Page for this controller.
  * Maps to the following URLhttp://example.com/index.php/hello
  - or - http://example.com/index.php/hello/index- or -* since this controller is set as the default controller in config/routes.php, it's displayed at http://example.com/
  * So any other public methods not prefixed with an underscorewill map to /index.php/welcome/<method_name>
  @see http://codeigniter.com/user_guide/general/urls.html
  public function index(){	    
    // Note that $view_params is optional// we can use $this->load->view('helloview');as well.// if the view doesn't use php variables 
    // The $view_params is extracted in the view script to php// variables $key = $value
    // In this example three variables will be generated by CI in the // view page
    // helloview.php variable: $mega_title
    // value: 'Codeigniter - Hello World'		// variable: $title      value: 'Welcome to // Codegniter'// variable: $message    value: 'Hello World'
    $view_params = array(
    'mega_title' => 'Codeigniter - Hello World', 'title'      =>  'Welcome to Codegniter','message'    =>  'Hello World'                              );		
			$this->load->view('helloview', $view_params);		}
	} // closing the class definition
/* End of file welcome.php *//* Location: ./application/controllers/welcome.php */

Tip

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

The view file

The following is the corresponding rendered view that uses the parameters provided by the controller to render the view to the web page and return it to the user:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title><?php echo $mega_title ?></title>
</head>
<body>
  <div id="container">
  <h1><?php echo $title ?></h1>
  <div id="body">
  <p><?php echo $message ?></p>
</div></div>
</body>
</html>
 

Example 2 – passing the complex parameters to a view


In this example, we will show you how to pass and use complex parameters, such as arrays and object arrays, from the CI controller to the rendered CI view to be used in the view. You can pass any number of arrays as parameters to a view; you can also pass objects, such as rows of a query result.

A standard GET parameters URI looks like this: http://ourdomain.com/index.php/example2/more/?a=1&b=2&c=3.

However, let's remember that in CI the URI is passed in this manner: http://ourdomain.com/index.php/example2/more/1/2/3. For more information, see Chapter 2, Configurations and Naming Conventions.

Looking at the URI, we will build the controller example2.php with the function named more with the three parameters passed to it.

We will build the following two scripts:

  • The controller class: application/controllers/example2.php

  • The view script : application/views/ example2more.php

The controller file

The controller is responsible for rendering the view with parameters such as mega title and message.

The following is the code sample of the controller:

<?php 
class Example2 extends CI_Controller {
  //This function gets parameters and passes them to the view//example2more
  //The example url//http://ourdomain.com/index.php/example2/more/1/2/3
  so $a = 1, $b = 2, $c = 3
  public function more($a, $b, $c)
  {
    // The parameters in $view_params are extracted in the view//example2more.php
    // In this example 2 variables will be generated by CI in the//view page example2more.php
    //variable: $mega_title, value: Codeigniter, Passing//url parameters to view
    variable: $rows, value: array('a' => $a, 'b' => $b, 'c' => $c);
    $rows = array('a' => $a, 'b' => $b, 'c' => $c);
    $view_params = array('mega_title' => 'Codeigniter -  Passing url parameters to view 'rows' => $rows);
    $this->load->view('example2more', $view_params);
    }	}// closing the class definition/* End of file welcome.php

The view file

The following is the corresponding rendered view:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title><?php echo $mega_title ?></title>
</head>
<body>
<table>
<tr>
  <td>Key</td>
  <td>Value</td>
</tr>
<?php foreach ($rows as $key => $value): ?>
<tr>
  <td><?php echo $key ; ?></td>
  <td><?php echo $value ; ?></td>
</tr> 
<?php endforeach; ?>
</table>
</body>
</html>
 

Example 3 – the database query by a model rendering results to a view


In this example, we will show you how the CI controller uses the CI model to retrieve data from the database and render it to a CI view.

The URL will be http://ourdomain.com/index.php/user.

First, we will have to configure the database settings in the configuration file application/config/database.php.

We should keep the default database settings unchanged, and only change the following configuration parameters:

$db['default']['hostname'] = '127.0.0.1';
//In many cases when the hostname's value is 'localhost' theconnection to the database fails.
//Setting the hostname to 127.0.0.1 solves the problem.
$db['default']['username'] = 'dbUser;
$db['default']['password'] = 'dbPassword';
$db['default']['database'] = 'dbDataAbse';
$db['default']['port']     = 'dbPort';

The model class will retrieve all the user details from the table users.

For more information on configurations, refer to Chapter 2, Configuration and Naming Conventions.

We will build the following three scripts:

  • The controller class: application/controllers/user.php

  • The model file: application/model/usermodel.php

  • The view script: application/views/userview.php

The controller file

The controller retrieves the users list from the database via the model and renders the view with it.

The following is the code sample of the controller:

<?php
class User extends CI_Controller {
  function users()
  {
    //Manually loading the database
    $this->load->database();
    //Loading the model class
    $this->load->model('Usermodel');
    $view_params['mega_title'] = 'Model Example';
    //Calling the model to retrieve the users from the database
    $view_params['users']= $this->Usermodel->get_users();
    $this->load->view('userview', $view_params);
  }
}
/* End of file welcome.php */
/* Location: /application/controllers/welcome.php */

The model file

The following is the code sample of the model.

<?php
class Usermodel extends CI_Model {
  function __construct()
  {
    // Call the Model constructor	parent::__construct();
  }
  //This method retrieves the users list and returns an array of //objects each containing user details
  function get_users()
  {
    //Calling CI's database object's method for generating SQL//queries.
    $query = $this->db->get('users');
    //returns an array of users objects
    return $query->result();
  }
}

In this example, the CI object database's method is called for generating and executing the SQL query.

Please refer to the CI database's library at http://ellislab.com/codeigniter/user-guide/database/index.html.

For more information about models, refer to Chapter 6, Models.

The view file

The view in this example shows the table content received from the controller containing the users list as defined in the database.

The following is the corresponding rendered view:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title><?php echo $mega_title ?></title>
</head>
<body>
<table>
<tr>
  <td>ID</td>
  <td>Name</td>
  <td>Email</td>
</tr>
<?php foreach ($users as $user): ?>
<tr>
  <td><?php echo $user->user_id ?></td>
  <td><?php echo $user->user_fname." ".$user->user_lname; ?></td>
  <td><?php echo $user->user_email ; ?></td>
</tr>
<?php endforeach; ?>
</body>
</html>
 

Example 4 – interactive contact forms


This example shows how to write a contact form using the CI form helper and the form_validation library.

For more information about libraries, refer to Chapter 4, Libraries, and for information about helpers, refer to Chapter 5, Helpers.

The CI controller defines a form validation setup using the form_validation library and renders a form view that uses the form_validation library setup to apply a desired validation on the submitted data by the user. If it's a success, the CI controller will render a view page displaying a success message, otherwise it will render the view page with the form and the error messages will be displayed.

The URI for this example is http://ourdomain.com/index.php/contact.

In order to perform this example, we shall build the following three scripts:

  • The contact form controller class: application/controllers/contact.php

  • The view form script: application/views/contactview.php

  • The view success page script: application/views/contactsuccess.php

The controller file

The controller creates a form for adding and editing a product.

For more information, refer to Chapter 7, Views.

The following is the code sample of the controller:

<?php
class Contact extends CI_Controller {
  public function index()
  {
    //Loading the form helper
    $this->load->helper('form');
    //Loading the form_validation library
    $this->load->library('form_validation');
    $view_params['form']['attributes'] = array('id' =>'myform');
    //contact name details
    $view_params['form']['contact_name']['label'] = array('text' => 'Your name:', 'for' => 'name');
    $view_params['form']['contact_name']['field']= array('name' => 'contact_name', 'id' => 'contact_name','value'=>isset($_POST['contact_name']) ?
    $_POST['contact_name'] : '',
    'maxlength' => '100', 'size' => '30', 'class' => 'input');
    //contact name details
    $view_params['form']['contact_email']['label'] = array('text' => 'Your email:', 'for' => 'email');
    $view_params['form']['contact_email']['field'] = array('name' => 'contact_email', 'id' => 'contact_email','value'=> isset($_POST['contact_email']) ?
    $_POST['contact_email'] : '',
    'maxlength'   => '100', 'size' => '30', 'class' => 'input');
    //contact message details
    $view_params['form']['contact_message']['label'] = array('text' => 'Your message:', 'for' => 'message');
    $view_params['form']['contact_message']['field'] = array('name' => 'contact_message', 'id' => 'contact_message','value' => isset($_POST['contact_message']) ?
    $_POST['contact_message'] : '',
    'rows' => '10',  'cols' => '100', 'class' => 'input');
    // Setting validation rules
    $config_rules = array(array('field' => 'contact_name','label' => 'Contact Name', 'rules' => 'trim|required'),
    array('field' => 'contact_email', 'label' => 'Contact Email','rules' => 'trim|required|valid_email'));
    $this->form_validation->set_rules($config_rules);
    $this->form_validation->set_rules('contact_message','Contact Message', 'trim|required');
    // Validating the form
    if ($this->form_validation->run() == FALSE)
    // failed 
    {
      for ($index = 0; $index < count($a_fields) $index++);
      {
        $s_field = $a_fields[$index];
        if (form_error($s_field))
        {
          $view_params['form'][$s_field]['field']['class'] .= 'error';
          }
        }
      $this->load->view('contactview', $view_params);
      }
      else // Validation succeeded
      {
      $success_params = array('message'=> 'Success');
      $this->load->view('contactsuccess', $success_params);
      }
    }
  }
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */

The view file

The view file displays the contact form for receiving data from the user.

The following is the corresponding rendered form view:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Form Example</title>
</head>
<body>
<?php if (validation_errors()) : ?>
  <?php echo validation_errors() ; ?>
  <?php endif; ?>
<?php echo form_open('contact', $form['attributes']) ; ?>
<table>
<tr>
  <td><?php echo form_label($form['contact_name']['label']['text'],
$form['contact_name']['label']['for']);?> 
  </td> 
  <td><?php echo form_input($form['contact_name']['field']); ?></td>
</tr>
<tr>
  <td><?php echo form_label($form['contact_email']['label']['text'],
$form['contact_email']['label']['for']);?>
  </td> 
  <td><?php echo form_input($form['contact_email']['field']);?>
  </td>
</tr>
<tr>
  <td><?php echo
  form_label($form['contact_message']['label']['text'],
  $form['contact_message']['label']['for']); ?>
  </td> 
  <td><?php echo form_textarea($form['contact_message']['field']);?>
  </td>
</tr>
<tr>
  <td colspan="3"><?php echo form_submit('mysubmit', 'Send'); ?></td>
</tr>
</table>
<?php echo form_close() ; ?>
</body>
</html>
The following is the corresponding rendered success view:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Contact sent</title>
</head>
<body>
<div id="container">
  <div id="body">
    <p><?php echo $message ?></p>
  </div>
</div>	
</body>
</html>
 

Summary


In this chapter we have reviewed the CI directory tree, especially the application folder, which is the heart and soul of any CI project. In the next chapter, we will review the configurations, such as database and naming conventions that are essential for the CI project.

About the Authors

  • Eli Orr

    Eli Orr brings over 30 years of experience in the high tech industry, mainly in software product development. Eli published articles in several magazines such as Wireless Systems Design, Telephony-Online, CommsDesign, EE Times, and for various emerging technologies. Currently, Eli is a PHP Advanced Web Application Developer, focused on CodeIgniter based projects for the last two years for rich functionality heavy-duty web applications. Prior to that, as an entrepreneur, Eli established LogoDial Zappix Ltd., and had the role of CTO and server-side developer. Zappix enables dynamic visualization of call center voice menus, which are currently available in USA and Israel on iOS and Android-enabled smartphones. Prior to that, Eli developed telecom solutions for Unified Communications with AT&T. Prior to that, Eli developed VoIP developer toolkits as a product manager with Radvision Ltd. During that period, he was an active member with the ITU-T Signaling Group 16 for defining VoIP protocol standardization, mainly the H.323. Prior to that, Eli led development teams with IAI (Israel Aircraft Industries) ELTA based C and C++ programming languages. Eli can be contacted through his website, http://EliOrr.com.

    Browse publications by this author
  • Yehuda Zadik

    Yehuda Zadik has over 20 years of experience in the IT industry, where he mainly specialized in software development based object-oriented programming (OOP) technologies. Yehuda has over 8 years of experience developing with PHP OOP and open source Linux environments for developing web-based applications. Yehuda used state-of-the-art technologies for building dynamic web-based applications that were e-commerce enabled as well as social network integrated. Yehuda has a vast knowledge for integrating third-party plugins for network, mobile, and social environments' integration. Among the environments, Yehuda integrated with Facebook API, LinkedIn API, and various others. Yehuda is an enthusiastic CodeIgniter developer who has been developing rich functionality and heavy traffic web-based applications over the last two years. Among Yehuda's clients are several major academic institutes. Yehuda can be contacted through his website, http://yudazdk.co.il.

    Browse publications by this author

Latest Reviews

(2 reviews total)
Sadly, as this book came to be released it was already out of date. Also, it has numerous errors and poor/lazy coding standards. I feel that the Tech Editors failed miserably in their task of oversight on this project. Lets just look at the code on pp15. 1. The first bullet point on this page has The controller class: application/controllers/user.php It should be User.php NOT user.php 2. The second bullet point includes "... application/model/user..." - This should be ... application/models/user.... 3. Last two lines are prefect example of lazy coding practice and should be: /* End of file User.php */ /* Location: /application/controllers/User.php Also very annoying and confusing when initially coming to grips with this book was the constant reference to a variable called curiously $mega_title instead of $meta_title. Important CI libraries such as form_validation are not dealt with in any detail - and I have only progressed to Chapter 1, Example 4.
Muy practico, se explica lo básico del framework y casos prácticos útiles en el desarrollo de aplicaciones
Book Title
Unlock this book and the full library for FREE
Start free trial