Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Programming with CodeIgniter MVC
Programming with CodeIgniter MVC

Programming with CodeIgniter MVC: Build feature-rich web applications using the CodeIgniter MVC framework

€22.99 €15.99
Book Sep 2013 192 pages 1st Edition
eBook
€22.99 €15.99
Print
€28.99
Subscription
€14.99 Monthly
eBook
€22.99 €15.99
Print
€28.99
Subscription
€14.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Sep 23, 2013
Length 192 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781849694704
Category :
Table of content icon View table of contents Preview book icon Preview Book

Programming with CodeIgniter MVC

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.

Left arrow icon Right arrow icon

Key benefits

  • Build feature-rich web applications using the CodeIgniter MVC framework
  • Master the concepts of maximum simplicity, separation, flexibility,reusability, and performance efficiency
  • A guick guide to programming using the CodeIgniter MVC framework

Description

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.

What you will learn

Install CodeIgniter and get acquainted with CodeIgniter resource directories Making your first web application Definiing your own CodeIgniter libraries Issuing AJAX calls of CodeIgniter controller methods Learning about controllers, helpers, and their usage Understandingthe CodeIgniter naming conventions Accessing CodeIgniter-assigned databases and other resources from your helpers

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Sep 23, 2013
Length 192 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781849694704
Category :

Table of Contents

15 Chapters
Programming with CodeIgniter MVC Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Authors Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
Getting Started Chevron down icon Chevron up icon
Configurations and Naming Conventions Chevron down icon Chevron up icon
Controller Usage and Scope Chevron down icon Chevron up icon
Libraries Chevron down icon Chevron up icon
Helpers Chevron down icon Chevron up icon
Models Chevron down icon Chevron up icon
Views Chevron down icon Chevron up icon
Appendix Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.