Embedding Model Data in Views with Code Igniter

Welcome to the conclusion of a seven-part series on handling views with the Code Igniter PHP framework. If you’re learning how to use the Model-View-Controller schema, this series of articles can help you get a better grasp of how to use it to quickly and dynamically generate web pages. In this part, we will finish building the database-driven application we discussed in the previous part.

Introduction

The intrinsic flexibility offered by the CodeIgniter framework gives PHP developers the ability to handle views in several clever ways. This feature allows you to easily generate dynamic sections of web pages. From loading views sequentially and using layout views, to nesting them within other views, CI offers plenty of options that permit you to quickly build front-ends without having to struggle with the schema dictated by the Model-View-Controller pattern.

However, for newcomers just starting to develop PHP applications with CodeIgniter, working with views in more complex ways can be challenging. Thus, if you’re stuck within a maze of controllers and don’t know how to make them interact with your views, then you should take a look at this group of articles, since they’ll show you different approaches that you can use for manipulating views in a truly efficient way.

And now that you’re well aware of the subject of this series of tutorials, it’s time to spend a moment refreshing the topics that were treated in the last article, in case you haven’t had the opportunity to read it yet. In that part, I explained how to build a simple database-driven application, whose main functionality was based on displaying on screen a few user-related records, previously fetched from a MySQL table.

In its current state, the structure of this sample application looked rather incomplete. It was comprised of a model and a controller class, where the first was responsible for retrieving user data from the table, and the second was charged with embedding this data in some view files, which actually haven’t been defined yet.

Therefore, in this final chapter of the series I’ll be creating these views, completing the development of this basic database-driven PHP program using CodeIgniter. By the end of this article, you’ll be equipped with a decent background not only in creating basic PHP applications with CI, but in manipulating views in an effective way.

Are you ready to tackle the last episode of this educational journey? Then, let’s get started right now!

{mospagebreak title=Review: the first two modules of the previous web application}

Before I proceed to build the three view files required to complete the PHP application created in the previous tutorial of this series, it would be useful to list the signatures of its model and controller classes, to help you recall more quickly how they were built.

That said, below I included these two classes. Have a look at them, please:

(‘user_model.php’ file – located at /application/models/ folder)


<?php

class User_model extends Model{

function User_model(){

// call the Model constructor

parent::Model();

// load database class and connect to MySQL

$this->load->database();

}

// fetch all users

function getAll(){

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

// return result set as an object array

return $query->result();

}

// fetch some users based on a predefined condition

function getWhere($field,$param){

$this->db->where($field,$param);

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

// return result set as an object array

return $query->result();

}

// get total number of users

function getNumber(){

return $this->db->count_all(‘users’);

}

}

?>



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


<?php

class WebPage extends Controller{

function WebPage(){

// load controller parent

parent::Controller();

// load users model

$this->load->model(‘User_model’);

// load some 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->User_model->getAll()),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);

}

}

?>


Undeniably, the tasks performed by both the model and controller classes are very easy to follow. First, the model has a few simple methods for counting and retrieving rows from a “user” MySQL table. On the other hand, the controller implements an “index()” method that uses the model’s “getAll()” method to generate the contents section of a web page.

Of course, it’s valid to point out here that each part of the web page being created is stored on a $data array, which is finally passed to a “main_page.php” view. All of these tasks, accomplished by the “WebPage” controller, naturally imply that the views need to be created accordingly.

Therefore, in the following section I’m going to build the first three views, which will be tasked with generating the header, content and footer sections of the web document.

To learn how this will be achieved, you’ll have to click on the link that appears below and read the section to come.

{mospagebreak title=Creating some basic view files}

If you already went through the preceding articles of this series, then you’re already familiar with building simple views. The views that I plan to build now will be really simple to grasp as well. As you’ll surely recall from the controller defined in the previous section, these views must be capable of generating independently the header, main area and footer section of a web page. This is actually very easy to accomplish. 

Here are the three views that render the web page in question:


(‘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 foreach($users 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;?>

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


As I said before, the signatures corresponding to the above views are fairly simple to understand. In this case, the “content_view.php” file is possibly the most complex to grasp, but all that it does is iterate over all the rows fetched from the pertinent “users” MySQL table and display the users’ first and last names, as well as their email addresses.

Due to the simple structure of the views coded before, I don’t want to spend more time explaining what they do, since that would be pretty pointless. However, as you may have noticed, there’s still one view that remains undefined, called “main_page.php,” which is precisely the one responsible for concatenating the other views.

Therefore, the last segment of the tutorial will be focused on creating this layout view, in this manner concluding this instructive journey on handling views with CodeIgniter. Now, if you want to see how this view will be coded, click on the link shown below and read the following section.

{mospagebreak title=Finishing the sample PHP application with CodeIgniter}

In the previous section, I created the three views that will be used for generating independently several section of a web page. Therefore, the last step that I’m going to take will consist of building the layout view, which was called “main_page.php.” Obviously, this particular file is tasked with concatenating the contents of the other views, meaning that its signature will be very simple to code.

Below you’ll see the entire source code corresponding to this layout file. Have a look at it, please:


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


If you were expecting to see a lengthy view, you might feel a little disappointed. Apart from including a few basic CSS styles, the above layout file contains only one “echo” PHP statement that appends the contents of the other views to generate the header, main area and footer section of the web page. Of course, this isn’t the only approach that can be utilized for building front-ends dynamically with CodeIgniter, but it certainly is a common one.

Finally, now that you’ve learned how to handle views in a few clever ways, feel free to tweak all of the code samples developed in this tutorial. Doing this should give you a more solid understanding of how to create web pages with CI. Whatever you do from this point onward, one thing is for sure: fun is already guaranteed!

Final thoughts

It’s really hard to believe, but we’ve come to the end of this series. If you’ve been a patient reader and examined in depth all of the code samples included in these tutorials, then by this time should have a clear idea of how to process views with CodeIgniter. As you can see, there is not just one right way to handle views; CI offers several approaches that can be used to suit the requirements of a specific PHP application.

From my point of view as a web developer, I find returning strings from views a very useful method for building web pages where static and dynamic contents are generated independently, but again, this is only a matter of personal preference.

See you in the next PHP development tutorial!

Google+ Comments

Google+ Comments