Handling Views with CodeIgniter

The Code Igniter framework makes it easy for developers to implement a Model-View-Controller design pattern in PHP. This concept can be difficult for newcomers to grasp, so this seven-part series of articles will focus on one aspect of it: views, and the many clever ways you can handle them with Code Igniter. Welcome to the first part.

Introduction

Any PHP developer who has spent a few weeks working with the CodeIgniter framework quickly discovers its many virtues. It has a relatively flat learning curve, and clear, thorough online documentation. Moreover, it lets users  implement the Model-View-Controller design pattern in a fairly strict fashion, and its flexible structure allows the extension of its core functionality via custom libraries, helpers and plug-ins.

Naturally, for seasoned CodeIgniter users, it’s a straightforward process to put all of these features to work together. For newcomers though, things tend to be more complicated, particularly when it comes to taking certain theoretical concepts inherent in the MVC schema and putting them into practice.

As soon as an inexperienced user starts developing a simple web application with CodeIgniter, he/she will be confronted with a number of common questions regarding the proper implementation and usage of Models, Controllers and Views. While learning how to work with Models and Controllers can be a challenging task, at least at first, the truth is that generating views seems to be much more approachable.

To clarify this concept a bit further, say that you’re building a web site comprised of a header section, a main area populated with some database contents, and finally a footer. In a case like this, the approach to be followed is pretty simple: on one hand you’d define a model that performs a few CRUD operations on your database, while on the other hand, there would be a controller that uses the model’s methods to fetch database rows, which would finally be embedded into some views to generate the different sections of the site.

In reality, implementing this view-centric method is actually pretty easy to achieve. However, CodeIgniter provides web developers with enough flexibility to handle views in all sort of clever ways. Therefore, in this series of articles I’ll be discussing in detail some common approaches that you can use to generate views, ranging from loading them sequentially, to using more complex methods, such as including views within other views.

Are you ready to learn how to handle views with CodeIgniter? Then let’s begin right now!

{mospagebreak title=Preparing views to be rendered on screen}

The first approach that I’m going to explore in this article involves loading views sequentially. To implement this specific method, I’m going to recreate a fictional scenario where an entire web page needs to be generated using the structure mentioned in the introduction. In this particular case, the header and footer sections will be static view files, while the main area will be filled in with dynamic content pulled out from a MySQL database.

Based on this scheme, it’s necessary to build the static files that will comprise this sample web page, that is, the header and footer parts. So, here are the two files that perform this task:


(definition of ‘header_view.php’ file)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Sample Web Page</title>

</head>

<body>

<div id="container">

<div id="header">

<h1><?php echo $header;?></h1>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>

</div>



(definition of ‘footer_view.php’ file)


<div id="footer">

<h2><?php echo $footer;?></h2>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</p>

</div>

</div>

</body>

</html>


So far, nothing unexpected, right? As you can see, the structure of the above two view files is pretty easy to follow. In the first case, the “header_view.php” file embeds only a $footer PHP variable into the markup, while the second file does something similar, since the “footer_view.php” view includes another variable called $footer.

As I explained before, these views could be considered the static sections of the web page that I plan to generate, even though each of them will contain some data that will be passed along via a still-undefined controller class.

Assuming that the latest version of CodeIgniter has already been installed on your testing web server, then the two previous view files should be saved to the /application/views/ folder of CI, so they can be found by its loader class at a later time.

Well, at this point I demonstrated how to build the header and footer views of a basic web page, which will be loaded via a sequential method. But, actually I’m getting ahead of myself, since first we need to define the view file that corresponds to the main area of the page. As I mentioned previously, this file will be populated with some database content.

Therefore, it’s time to build this additional view file. This process will be discussed in depth in the section to come, so click on the link that appears below and read the following segment.

{mospagebreak title=Creating a content view}

In the previous section, I explained how to build a couple of static views that will be used later on for generating the header and footer parts of a simple web page. However, the only view file that remains undefined is the one tasked with rendering the main area of this page. In this situation, I’m going to populate this area with content from a MySQL table called “users,” which I also used in some other PHP articles published here at the prestigious Developer Shed network.

As a quick reminder, the structure of this table looked like this:



Now that you hopefully recalled how this example table was filled with some trivial records, it’s time to build the view file that loops over each of them. Here it is:


<div id="content">

<?php if($users->num_rows > 0):?>

<?php foreach($users->result() as $user):?>

<p><strong>First Name: </strong><?php echo $user->firstname;?></p>

<p><strong>Last Name: </strong><?php echo $user->lastname;?></p>

<p><strong>Email: </strong><?php echo $user->email;?></p>

<hr />

<?php endforeach;?>

<?php endif;?>

</div>


Undoubtedly, the above view should be fairly easy to grasp for you, since all that it does is iterate over each user fetched from the previous MySQL table and display their first and last names, and their email address, on screen. Before I forget, please save this view under the /application/views/ folder of CodeIgniter, so it can be used later on.

Done? Great. Having created the view file that generates the dynamic section of the sample web page, the next step I’m going to take will consist of defining a simple controller class. As you’ll see in a moment, this controller will be responsible for loading the three views in a sequential fashion, in this way generating the entire web document.

This procedure will be shown in the upcoming section of this article, so if you wish to learn more, please read the next few lines.

{mospagebreak title=Building a web page controller class}

To be frank, generating an entire web document by sequentially loading the three views that you saw before is a no-brainer process that you’ll grasp in a snap. But how can it be done? Well, first it’s necessary to define a controller class that performs this specific task. In this case, since I’m attempting to create a web page, the controller will be called “WebPage” (my creativity with names sometimes blows me away) and it’ll look like this:


<?php

class WebPage extends Controller{

function WebPage(){

// load controller parent

parent::Controller();

// load libraries here

$this->load->database();

// load helpers here

}

// load views sequentially

function index(){

// load ‘header’ view

$this->load->view(‘header_view’,array(‘header’=>’Header Section’));

// load ‘content’ view and pass in database content

$this->load->view(‘content_view’,array(‘users’=>$this->db->get(‘users’)));

// load ‘footer’ view

$this->load->view(‘footer_view’,array(‘footer’=>’Footer Section’));

}

}

?>


See how simple it is to build a web page by loading views in a sequential manner? The controller defined above demonstrates this process pretty clearly, since it firsts loads the CI’s database class within its constructor, and then  proceeds to build the different sections of the page by loading in turn each of the previous views. Simple and efficient.

Now that you hopefully understood how the “WebPage” controller works, save it under the “/application/controllers/ folder and type the following URL on your browser’s address field to test it: http://localhost/codeigniter/index.php/webpage/


If everything goes well, you should get the following output on screen:



There you have it. At this stage you’ve learned how to sequentially load three different views to generate a basic web page. Logically, there’s plenty of room to improve the signature of the controller or even the views themselves. But guess what? This will be left as homework for you.

Final thoughts

In this first episode of the series, I explained how to build different sections of a basic web page with CodeIgniter by sequentially loading three independent view files. It could be said that this approach is possibly the simplest to implement when handling views with CI, but as I said in the beginning, it’s not the only one.

In the next article, I’ll be polishing the visual appearance of the web page generated previously to make it look slightly more appealing. Now that you’ve been warned about the topic that will be covered in the forthcoming part of the series, don’t miss it!

Google+ Comments

Google+ Comments