Moving Presentation Logic Out of Views with Code Igniter

Manipulating views with CodeIgniter is a straightforward process. In a typical situation, there’s a model that fetches some rows from one or more database tables, and a view file that receives this data through a controller class, which is finally displayed on screen, generally in the form of an HTML page. However, CodeIgniter gives PHP programmers enough freedom to handle views in several useful ways, which can speed up the development of web applications. Therefore, if you’re taking your first steps with CI and wish to learn some handy approaches that will help you work with views in a truly painless fashion, then start reading this tutorial now!

Introduction

At this point, after having introduced you to the subject of this series of articles, it’s time to recall the topics we discussed in the last tutorial, in case you still haven’t had the chance to read it. In summary, in that article I proceed to build a simple MySQL-driven application whose main task consisted of fetching some database rows and embedding this data into a basic view file.

Apart from playing a bit with the schema dictated by the Model-View-Controller pattern, this particular example showed in a nutshell how to return strings from the “$this->load->view()” method to create different parts of a web page, such as the typical header and footer sections, and a main area as well.

In addition, you’ll possibly recall that the view that displayed the database records implemented a simple presentation logic, reduced to looping over the records in question and nothing else. It’s also possible to make this view even “dumber” by moving this looping structure out of it, in this way achieving a greater level of separation between the application’s logic and its presentation layer.

Therefore, in this fifth part of the series, I’ll be rebuilding the web application that you learned in the last article, modifying the view file responsible for displaying database rows on the web page.

Do all these things sound interesting enough for you? Then let’s get started right now!

{mospagebreak title=Review: returning values with a previous method}

In the introduction, I mentioned that it’s possible to remove from a view the PHP loop that iterates over the database rows, based on the structure of the web application developed in the previous article. But before I show you how to do that, I’m going to reintroduce the full source code of this sample PHP program, so you can recall how it was developed initially.

That being said, here are all the files that comprise this web application:


(‘webpage.php’ file – located at /application/controllers/ folder)

<?php

class WebPage extends Controller{

function WebPage(){

// load controller parent

parent::Controller();

// load libraries here

$this->load->database();

// load helpers here

}

// generate web page using partial sections

function index(){

// generate header section

$data['header']=$this->load->view(‘header_view’,array(‘header’=>’Header Section’),TRUE);

// generate content section

$data['content']=$this->load->view(‘content_view’,array(‘users’=>$this->db->get(‘users’)),TRUE);

// generate footer section

$data['footer']=$this->load->view(‘footer_view’,array(‘footer’=>’Footer Section’),TRUE);

// generate full web page

$this->load->view(‘main_page’,$data);

}

}

?>



(‘main_page.php’ file – located at /application/views/ folder)


<!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>

<style type="text/css">

body{

padding: 0;

margin: 0;

background: #999;

}

#container{

width: 600px;

margin: 0 auto;

}

#header{

padding: 10px;

background: #eee;

}

#content{

padding: 10px;

background: #9cf;

}

#footer{

padding: 10px;

background: #eee;

}

h1{

font: bold 2em Arial, Helvetica, sans-serif;

margin: 0 0 18px 0;

color: #039;

}

h2{

font: bold 1.5em Arial, Helvetica, sans-serif;

margin: 0 0 18px 0;

}

p{

font: normal .8em Arial, Helvetica, sans-serif;

margin: 0 0 18px 0;

}

</style>

</head>

<body>

<div id="container">

<?php

echo $header.$content.$footer;

?>

</div>

</body>

</html>



(‘header_view.php’ file – located at /application/views/ folder)


<div id="header">

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

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut.</p>

</div>



(‘content_view.php’ file – located at /application/views/ folder)


<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>



(‘footer_view.php’ file – located at /application/views/ folder)


<div id="footer">

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

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut.</p>

</div>


Having listed all of the source files that compose the MySQL-driven application built during the previous tutorial of this series, it’s worthwhile to stress one point regarding the way it’s been structured: as you can see, within the “content_view.php” view file there’s a “foreach” construct that loops over the rows fetched from a “users” MySQL table.

This is a valid approach, used frequently for constructing views. However, it’s also feasible to implement a little twist here and remove the loop from this specific view, in this way increasing the level of separation between the application’s logic and its visual presentation even more.

Provided that you’re interested in learning how to turn the concept deployed above into functional code, in the next section I’ll be creating a brand new view file, in addition to modifying slightly the signature of the “WebPage” controller class.

Click on the link below and continue reading.

{mospagebreak title=Moving presentation logic out of views}

Since in this case I’m planning to move the “foreach” loop included within the “content_view.php” file out of it, the simplest way to do that is by implementing this part of the application straight into the controller. To demonstrate how to achieve this, below I listed the modified signature of the “WebPage” controller class, which now looks like this:


<?php

class WebPage extends Controller{

function WebPage(){

// load controller parent

parent::Controller();

// load libraries here

$this->load->database();

// load helpers here

}

// generate web page using partial sections

function index(){

// generate headers section

$data['header']=$this->load->view(‘header_view’,array(‘header’=>’Header Section’),TRUE);

$query=$this->db->get(‘users’);

if($query->num_rows > 0){

// generate content section

$data['content']=NULL;

foreach($query->result() as $user){

$data['content'].=$this->load->view(‘users_view’,array(‘user’=>$user),TRUE);

}

}

// generate footer section

$data['footer']=$this->load->view(‘footer_view’,array(‘footer’=>’Footer Section’),TRUE);

// generate full web page

$this->load->view(‘main_page’,$data);

}

}

?>


As shown above, the logic implemented by the “WebPage” controller practically remains the same, except for a tiny detail: now the “foreach” loop included previously within the “content_view.php” file has been moved within the controller, and in consequence it’s necessary to create a new view that displays the data retrieved from the “users” MySQL table.

The signature of this new view file, called ”users_view.php,” looks as simple as this:


<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 />


Here you have it. Now the controller is responsible for looping over the rows fetched from the MySQL table, and the result is stored on the $data[‘content’] array element. Lastly, each section of the web page is embedded into the “main_page.php” view, which finishes rendering the whole web document. Not too hard to understand, right?

Having implemented an alternative approach to building a basic MySQL-based web application, now it’s time to put all of its pieces together, since two of its files were modified. Thus, in the last section of this tutorial I’ll be listing for you the full source code of this sample PHP program, so you can copy/paste it and introduce your own improvements.

Now, jump forward and read the next few lines. We’re almost finished!

{mospagebreak title=The modified source code of the sample PHP program}

Having demonstrated how simple it is to remove (at least partially) the presentation logic from a view file and delegate part of this task to the controller, here are all the source files corresponding to this sample PHP application, after we’ve introduced the changes that you learned in the prior section.

Take a look at them, please:


(‘webpage.php’ file – located at /application/controllers/ folder)


<?php

class WebPage extends Controller{

function WebPage(){

// load controller parent

parent::Controller();

// load libraries here

$this->load->database();

// load helpers here

}

// generate web page using partial sections

function index(){

// generate headers section

$data['header']=$this->load->view(‘header_view’,array(‘header’=>’Header Section’),TRUE);

$query=$this->db->get(‘users’);

if($query->num_rows > 0){

// generate content section

$data['content']=NULL;

foreach($query->result() as $user){

$data['content'].=$this->load->view(‘users_view’,array(‘user’=>$user),TRUE);

}

}

// generate footer section

$data['footer']=$this->load->view(‘footer_view’,array(‘footer’=>’Footer Section’),TRUE);

// generate full web page

$this->load->view(‘main_page’,$data);

}

}

?>



(‘main_page.php’ file – located at /application/views/ folder)


<!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>

<style type="text/css">

body{

padding: 0;

margin: 0;

background: #999;

}

#container{

width: 600px;

margin: 0 auto;

}

#header{

padding: 10px;

background: #eee;

}

#content{

padding: 10px;

background: #9cf;

}

#footer{

padding: 10px;

background: #eee;

}

h1{

font: bold 2em Arial, Helvetica, sans-serif;

margin: 0 0 18px 0;

color: #039;

}

h2{

font: bold 1.5em Arial, Helvetica, sans-serif;

margin: 0 0 18px 0;

}

p{

font: normal .8em Arial, Helvetica, sans-serif;

margin: 0 0 18px 0;

}

</style>

</head>

<body>

<div id="container">

<?php

echo $header.$content.$footer;

?>

</div>

</body>

</html>



(‘users_view.php’ file – located at /application/views/ folder)


<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 />



(‘footer_view.php’ file – located at /application/views/ folder)


<div id="footer">

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

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut.</p>

</div>


If you already have a fresh installation of CodeIgniter working on your web server, then when you type the following URL on your browser:


http://localhost/codeogniter/index.php/webpage


You should get the following output echoed to the screen:



Regardless of the simple structure of this sample PHP application, it’s useful for demonstrating another approach when it comes to handling views with CodeIgniter. As usual with other articles of this series, feel free to tweak all of the code samples shown in this article. This will help you understand more quickly how to create view files that include only basic presentation logic.

Final thoughts

In this fifth part of the series, I demonstrated yet another approach that can be used for partially removing presentation logic from views. Despite the fact that this method isn’t as intuitive as others utilized in previous articles, it might be appealing to you. Again, it’s valid to say that there’s not an official way to work with CodeIgniter, and it depends on you what approach to use when developing your own PHP applications.

Now, returning to the examples developed so far in this series, you may have noticed that none of them have utilized a model to access the “users” MySQL table. It’s not mandatory to code a model with CI, particularly if the program you’re planning to build is fairly basic or your implementation of the MVC pattern is loose.

However, in the next chapter of this series I’ll be defining a model, which will be incorporated into the PHP program developed earlier. Want to see how this will be done? Then, don’t miss the forthcoming part!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan