Defining a Model Class for Handling Views with CodeIgniter

Welcome to the sixth installment of a seven-part series on handling views with the CodeIgniter PHP framework. This series shows you a few handy approaches that you can implement quickly within your CI-based programs to work with view files in a truly clever way, ranging from loading them sequentially to nesting views within other views.

And now that you’re aware of the topics that are covered in this group of articles, it’s time to review the concepts discussed in the last tutorial. In that part, I used a practical example to show you how to partially remove presentation logic from a particular view file, and implement it within a simple controller class.

As with many other aspects related to using the Model-View-Controller pattern with CodeIgniter, making views a bit “dumber” has its pros and cons. How successful this approach can be in the end depends strongly on the structure defined for a particular application. Again, it’s fair to mention here that CI gives developers enough flexibility to implement the MVC pattern without forcing the use of a specific programming methodology. Indeed, this is one of its most appreciated characteristics.

Now, returning to the previous tutorial, you’ll recall that I developed a sample PHP application. It displayed the contents of some database rows which were previously fetched from a “users” MySQL table. Moreover, these rows were retrieved by using the active record class bundled with CI.

However, it’s also possible to define a model that performs all of the database-related operations, instead of directly using the database class. Thus, in the next few lines I’m going to show you how to build another web application similar to the one that you learned in the preceding article — but this time it will incorporate a basic model class. In doing so, you’ll be able to see how to handle views by using the entire Model-View-Controller triad.

Are you ready to continue learning how to parse views with CodeIgniter? Then let’s jump right in!

{mospagebreak title=Review: moving presentation logic out of views}

If you’re like me, then you can’t wait to see how a model can be used for interacting with the “users” MySQL table that you saw in the prior tutorial. Before you learn that, however, I’m going to list all of the source files corresponding to the web application developed in the previous article, so you can clearly see the differences between using a model and using the CI’s database class directly.

Having clarified that point, here’s the complete source code for this sample PHP program:

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

In this case, three views and a basic web page controller class are the only building blocks required for developing a web application whose main task is to display the contents of the “users” MySQL table on screen. As I stated before, the controller directly uses the database class for retrieving database rows, which are properly parsed before being embedded into the “main_page.php” view file.

Undoubtedly, the above approach demonstrates in a nutshell how to partially remove some presentation logic from a view, but it’s not the only method that you may want to use for handling views with CodeIgniter.

Now that you’ve hopefully recalled how the web application shown a few lines before was built by using a single controller class and some additional views, it’s time to move on. We’re going to start defining a users model class, which will be tasked with retrieving database rows from the already familiar “users” MySQL table. Of course, creating a model implies that the signature of the controller must be modified to work with it, but don’t worry about this for the moment. Simply proceed to read the following section, where I’m going to explain how to build this model class.

Now, click on the link that appears below and read the next segment.

{mospagebreak title=Handling database contents with a simple model class}

In the preceding segment, I mentioned that it was perfectly possible to incorporate a model class to access database contents, instead of directly using the database class included with CodeIgniter. So, to put this theoretical concept into practice, below I created such a class. In this case, it is charged with fetching some rows from the “users” MySQL table that you learned before, and with counting its records as well.

In summary, this model class, called “User_model,” is defined in the following way:


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

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 object

return $query->result();

}

// get total number of users

function getNumber(){

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

}

}

?>


In reality, understanding how the above “User_model” class works is a pretty straightforward process, don’t you think? As you can see, this model implements a few basic methods for retrieving users from the corresponding database table, and for counting them as well. Naturally, it’s feasible to aggregate more methods that perform inserts, updates and deletions, but for now I’ll keep the signature of the model simple.

So far, so good. At this point, I showed you how to build a basic model class that will be responsible for fetching user-related data from the pertinent MySQL table. Therefore, the next step is to change the signature of the “WebPage” controller class so that it can use the model for accessing database contents.

This modification will be discussed in detail in the last section of this tutorial. Therefore, please click on the link below and read the upcoming segment.

{mospagebreak title=Demonstrating a simple use of the model class}

Since in the previous section I created a basic model class that permits us to fetch and count users stored on a MySQL table, the next thing I’m going to do will be modifying the signature of the corresponding “WebPage” controller so that it can use the model’s methods from behind its API.

Having explained that, here’s how the controller now looks:


<?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);

}

}

?>


Simple to code and read, isn’t it? As shown above, now the “index()” method of the controller generates the header, body and footer parts of a web page, but this time the body section is populated with database contents that are fetched via the “getAll()” method that belongs to the model.

At this stage, not only does the controller show how to utilize the methods given by a specific model, but the example illustrates how to assemble an entire web page by returning different strings from the “$this->load->view()” method.

The missing pieces of this schema are the three view files that actually render the web page in question. However, these will be created in the last article of the series. Meanwhile, feel free to edit and enhance the respective signatures of the model and the controller to acquire a more solid grounding in developing database-driven applications with CodeIgniter.

Final thoughts

Over this sixth episode of the series, I went through building a basic model class with CodeIgniter. This class was incorporated into a simple PHP application whose primary functionality was displaying information on screen about some users stored on a MySQL table.

Logically, at this point the application is still incomplete, since it is necessary to create three different views that will be responsible for generating independently the header, main area and footer section of the web page where user-related data will be echoed. Those views will be built in the last tutorial.

So here’s a piece of advice that you should consider seriously: don’t miss the final article!

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort