Wednesday, 21 September 2016

How to Creating a Custom Controller and View in CodeIgniter

This is lesson eight of a 10 ten-lesson course, Simple CodeIgniter App, which walks you through the creation of your first PHP web application using the CodeIgniter framework.


We’ve spent a few previous lessons establishing our database and learning how to retrieve information from it, and now, it’s finally time to complete the circle and actually display some of that data!
Ultimately, we’ll be creating a page to display a list of all of the todos in our database, as shown in the mockup below.

The four essential pieces

When it comes to displaying actual data to a user in a web app, there are four pieces of the puzzle:
  • database, to store the data;
  • model, to represent the data objects and interact with the database;
  • controller, to retrieve the necessary data (leveraging the model(s)) and organize it;
  • and a view, to actually render and display the data.
…which means we’re halfway there, as we already have a database and a model. Let’s go ahead and get all of the way there.

Creating a new controller

The very first thing we need to do is create a controller so that we can get access to the data our model is helping us retrieve.
Start off by creating a new controller for our todos in the application/controllers directory named todos.php with code here:

A diagram of the MVC pattern depicting the information flow between a user’s browser, and the controller, model, view, and database
Now we have our controller, but we still need to add a new action that can be associated with a specific URL, in order to eventually display our data on a page.

Adding a controller action

Now it’s time to create an action and start adding actual functionality to it. Go ahead and alter the controller’s code to include a new index action, as shown here:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Todos extends CI_Controller {

  public function index()
  {
    // 1. Load the data:
    // 2. Make the data available to the view
    // 3. Render the view:
  }

}
As you can see based on the comments, there are three things we’ll need to do in our action: load the necessary data (via the Todo_model we established in lesson 7); make the data available to the view; load/render the view.
But before we can load our data from the Todo_model, we first need to create a way for our controller to communicate with our model, because right now, it doesn’t know how to do that.

Prerequisite: Loading our model

Just as in our model, in any controller in CI, you also have the ability to define a constructor that is executed every time the controller is accessed (such as when a user requests a page that’s managed by the controller).
Since our goal is to load our model and make it available to all of the controller’s actions (even though there’s only one, now), a constructor is exactly what we need.
Go ahead and add the constructor method to the top of the Todos controller, shown here:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Todos extends CI_Controller {

  public function __construct() {
    parent::__construct();
    
    // Load the todo model to make it available 
    // to *all* of the controller's actions 
    $this->load->model('Todo_model');
  }
  .
  .
  .
}
The following line is responsible for loading the model:
$this->load->model('Todo_model');
And since it’s contained within the constructor, that means that all of our controller’s actions will have the ability to access it using $this->Todo_model, as we’ll see in just a minute.

Retrieving data via our model

By loading our model in the constructor, we can now access it within our controller actions using$this->Todo_model.
In our Todo_model, we previously created a function to retrieve all of our todos, aptly namedget_all_entries, with the newest todos appearing first. Go ahead and add the following code to our index action, which utilizes that very function:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Todos extends CI_Controller {
  .
  .
  .
  public function index()
  {
    // 1. Load the data:
    $all_todos = $this->Todo_model->get_all_entries(); 

    // 2. Make the data available to the view

    // 3. Render the view:

  }

}
As you may already be aware, the code we just added makes a call to the get_all_entriesfunction in our Todo_model and stores the entries retrieved in a new $all_todos variable.

Preparing the data to be passed to the view

We have our todos stored in $all_todos. Great.
But how will our view be able to access the todos? That’s exactly what we’re going to address right now.
As you’ll see in step 3 when we load/render a view, we have the ability to pass it an array—a collection of items—that will be accessible within the view file itself. All we have to do, in preparation for loading our view, is create a new array, and add our todos to that array.
In order to accomplish that, add the following code to the index action:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Todos extends CI_Controller { 
  .
  . 
  .
  public function index()  {
    // 1. Load the data:
    $all_todos = $this->Todo_model->get_all_entries();

    // 2. Make the data available to the view
    $data = array();   
    $data['todos'] = $all_todos;

    // 3. Render the view:

  }

}
Our new $data array now contains our todos, and we’ll be able to pass it to our view when we load it.

4 comments:

  1. How to Creating a Custom Controller and View in CodeIgniter ?

    ReplyDelete
  2. How to Creating a Custom Model and View in CodeIgniter

    ReplyDelete
  3. how to define global array in codeigniter?

    ReplyDelete
  4. Githut lists its ranking according to the following characteristics: active repositories, the number of pushes and the pushes per repository, as well as the new forks per repository, the open issues per repository and the new watcher per repository.

    GitHut’s top 20 ranking currently looks like this:

    JavaScript
    Java
    Python
    Ruby
    CSS
    PHP
    C++
    C
    Shell
    C#
    Objective-C
    R
    VimL
    Go
    Perl
    CoffeeScript
    TeX
    Scala
    Haskell
    Emacs Lisp

    If we compare it with the programming community index, Tiobe (who published the following ranking in its September issue) the results are quite different.

    C
    Java
    Objective-C
    C++
    C#
    Basic
    PHP
    Python
    JavaScript
    Transact-SQL
    Visual Basic .NET
    Perl
    Ruby
    Visual Basic
    Delphi/Objective Pascal
    F#
    Pascal
    Swift
    MATLAB
    PL/SQL

    While Java still remains a strong player in both rankings, it is interesting to note that since this time last year, Java has slipped off the number one spot on Tiobe’s list.

    You can see noticeable differences between the two lists, especially in relation to the relativity of rankings. Tiobe compiles search engine inquiries with the number of developers, courses and providers for evaluation. GitHut has the advantage of not relying on such vague criteria and it can use verifiable data of official APIs. But what relationship does GitHub data have to the worldwide distribution of programming languages?

    ReplyDelete