PHP MVC Frameworks: Building View Files

In this next-to-last part of the series, I finish building a MySQL-driven application that uses the functionality of the framework we’ve created to perform CRUD operations on a database table populated with user-related data.

Learning how to successfully implement a number of design patterns is definitely a great idea for PHP coders whose main goal is to develop solid and efficient web applications. This includes using the popular Model-View-Controller triad, or expressed in programming jargon, the MVC pattern.

True to form, this pattern is a helpful paradigm that will let you build programs that keep their application and business logic isolated from their visual presentation. This implies that they can be scaled up much more easily as they grow both in size and complexity.

However, grasping the theoretical concepts that surround the application of this pattern, especially in the terrain of web development, is only half of the whole learning process. It’s necessary to demonstrate how it can be used in a real-world project as well.

This series of articles attempts to tackle this last point. It shows you how to leverage the power of the MVC design pattern to construct an extensible framework in PHP 5, which you can use as the starting point to create your own, or simply to understand more clearly the internal functioning of other well-consolidated frameworks available nowadays.

If you’ve reached this point you probably have an excellent idea not only of how to build a framework like the one mentioned above, but how to use many of its components for developing a basic MySQL-driven application capable of performing CRUD operations on a database containing records about some fictional users.

Speaking more specifically, I left off the last part of the series explaining how to build a controller class that first used the API of the framework’s model to run the aforementioned operations, and then to generate the appropriate outputs on the browser by way of a view class.

But as you’ll surely recall, the view files responsible for outputting formatted data to the screen weren’t created yet. In the next few lines I’m going to code them, so you can see how to use the HTML form helper class included in the framework.

Ready to tackle this penultimate installment of the series? Then begin reading now!

{mospagebreak title=Review: the user controller class}

Before we start coding the view files required by the user controller class created in the previous tutorial, it’d be useful to recall the definition of this component of the framework. This way, you can see how easy it is to build an application that sticks to the MVC design pattern.

The file containing the definition of the user controller mentioned in the introduction was built like this:

(UsersController.php)

<?php

class UsersController

{

private $model = NULL;

 

// constructor

public function __construct()

{

// store model object as property

$this->model = new Model(MySQL::getInstance(array(‘host’, ‘user’, ‘password’, ‘database’)));

}

// fetch and display all users

public function index()

{

// create view object

$view = new View(‘users’);

// create view properties

$view->title = ‘Using the MVC design pattern with PHP 5′;

$view->heading = ‘User List’;

$view->users = $this->model->fetchAll();

// display view

echo $view->display();

}

// create new user

public function create()

{

// create view object

$view = new View(‘user_form’);

// create view properties

$view->title = ‘Using the MVC design pattern with PHP 5′;

$view->heading = ‘Create new user’;

// display view

echo $view->display();

}

 

// save user

public function save()

 {

// get POST params

if (Input::post(‘send’))

{

$fname = Input::post(‘fname’);

$lname = Input::post(‘lname’);

$email = Input::post(‘email’);

// save user data

$this->model->save(array(‘fname’ => $fname, ‘lname’ => $lname, ‘email’ => $email));

}

}

// update existing user

public function update($id)

{

$this->model->save(array(‘fname’ => ‘My first name’, ‘lname’ => ‘My last name’, ‘email’ => ‘myemail@domain.com’), (int)$id);

}

// delete existing user

public function delete($id)

{

$this->model->delete((int)$id);

}

}// End UsersController class

As you can see, the user controller class is comprised of a few straightforward methods that allow you to retrieve, insert, update and delete records on a MySQL table populated with data on some fictitious users via the model’s API, including their first and last names, and their email addresses as well.

Of course, due to the inherent flexibility offered by the model, switching between different database tables is a breeze, but for the illustrative purposes of this tutorial I’ll keep using the table that stores only user data.

So far, so good, right? At this stage, you understand the underlying logic of the previous controller class, which also makes use of other components of the framework, such as the input and view classes, to do its business.

However, the instantiation of view objects within the controller implies a direct inclusion of view files that output something to the browser. In this case, the process occurs in the “index()” and “create()” methods respectively. Obviously, it’s necessary to define these files to get this sample PHP application working as expected, so in the following section I’m going to do precisely that.

Now, to learn more about this process, click on the link that appears below and keep reading.

{mospagebreak title=Generating browser output with view files}

As I explained in the segment that you just read, the user controller class implements two methods that render HTML on screen by means of two view files. The first one is “index(),” which is tasked with displaying all of the users stored in the corresponding MySQL table, while the second one is “create(),” which is responsible for outputting an HTML form for entering data about a new user.

In accordance with this, I’m going to create the file that displays user data on screen, which will be called “users.php.”

The definition of this file is as follows:

(users.php)

<!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=UTF-8"/>

<title><?php echo $title;?></title>

</head>

<body>

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

<?php if (empty($users)):?>

<h2>Oops! There are not users in the database.</h2>

<?php else:?>

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

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

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

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

<hr />

<?php endforeach?>

<?php endif?>

</body>

</html>

Nothing really spectacular, right? As you can see, this view file that displays the list of users stored in the MySQL table is simply a mixture of HTML and interspersed PHP code, which in this case comes in handy for traversing a result set and showing information about each user.

This file, along with the other one that I’m about to show you, put in evidence the need for adding to the framework a view helper that sanitizes output, in order to prevent XSS attacks. This will be left as homework for you.

Now, it’s time to list the view file that creates the HTML form used for inserting new users into the database. This one is called “user_form.php,” and looks like this:

(user_form.php)

<!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=UTF-8"/>

<title><?php echo $title;?></title>

</head>

<body>

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

<?php echo Form::open(array(‘action’ => ‘save’, ‘method’ => ‘post’));?>

<p>First Name: <?php echo Form::input(array(‘type’ => ‘text’, ‘name’ => ‘fname’));?></p>

<p>Last Name: <?php echo Form::input(array(‘type’ => ‘text’, ‘name’ => ‘lname’));?></p>

<p>Email: <?php echo Form::input(array(‘type’ => ‘text’, ‘name’ => ‘email’));?></p>

<p><?php echo Form::input(array(‘type’ => ‘submit’, ‘name’ => ‘send’, ‘value’ => ‘Create user’));?></p>

<?php echo Form::close();?>

</body>

</html>

Definitely, this file is slightly more interesting than the previous one, as it uses the “Form” helper class that you saw in previous tutorials for rendering the different parts of the form that insert a new user in the MySQL table. Also, notice that the “action” attribute of the web form points to the “save()” method in the controller, which simply takes the collected data and inserts it directly into the database table.

Now that the two view files used by the controller class have been properly defined, you can try this sample application. So, say that you want to list all of the users stored in the database. To do that (assuming that the framework’s components and the application’s classes reside in a folder called “mvc” on the web server), you should type the following URL into your browser:

http://localhost/mvc/users

If all goes well, you will see the lists of users displayed on the browser. On the other hand, if you wish to add a new user to the database, you should enter the following:

http://localhost/mvc/users/create

It’s simple to read and SEO-friendly. Naturally, under normal conditions, direct calls to controllers and methods should be done through regular HTML links, but remember that this is only an illustrative example and nothing else. Anyway, adding those links would be as simple as including them in the appropriate view files.

Well, at this point, this sample MySQL-driven application is working as expected, thanks to the proper use of the classes provided by the framework. Thus, I’m going to end this tutorial of the series by showing in one single place all of these recently-created files, so you can study them in more detail.

Now, go ahead and read the following section. We’re almost finished here!

{mospagebreak title=The sample application’s files}

As I promised in the previous section, here’s the list of files that compose this sample MySQL-driven application, this time including the corresponding user controller class and the pair of view files coded before.

First, here’s the controller:

(UsersController.php)

<?php

class UsersController

{

private $model = NULL;

 

// constructor

public function __construct()

{

// store model object as property

$this->model = new Model(MySQL::getInstance(array(‘host’, ‘user’, ‘password’, ‘database’)));

}

// fetch and display all users

public function index()

{

// create view object

$view = new View(‘users’);

// create view properties

$view->title = ‘Using the MVC design pattern with PHP 5′;

$view->heading = ‘User List’;

$view->users = $this->model->fetchAll();

// display view

echo $view->display();

}

// create new user

public function create()

{

// create view object

$view = new View(‘user_form’);

// create view properties

$view->title = ‘Using the MVC design pattern with PHP 5′;

$view->heading = ‘Create new user’;

// display view

echo $view->display();

}

 

// save user

public function save()

 {

// get POST params

if (Input::post(‘send’))

{

$fname = Input::post(‘fname’);

$lname = Input::post(‘lname’);

$email = Input::post(‘email’);

// save user data

$this->model->save(array(‘fname’ => $fname, ‘lname’ => $lname, ‘email’ => $email));

}

}

// update existing user

public function update($id)

{

$this->model->save(array(‘fname’ => ‘My first name’, ‘lname’ => ‘My last name’, ‘email’ => ‘myemail@domain.com’), (int)$id);

}

// delete existing user

public function delete($id)

{

$this->model->delete((int)$id);

}

}// End UsersController class

Now it’s time to show the first view file, so here it is:

(users.php)

<!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=UTF-8"/>

<title><?php echo $title;?></title>

</head>

<body>

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

<?php if (empty($users)):?>

<h2>Oops! There are not users in the database.</h2>

<?php else:?>

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

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

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

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

<hr />

<?php endforeach?>

<?php endif?>

</body>

</html>

And finally, here’s the second view file; it displays an HTML form using the framework’s form helper:

(user_form.php)

<!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=UTF-8"/>

<title><?php echo $title;?></title>

</head>

<body>

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

<?php echo Form::open(array(‘action’ => ‘save’, ‘method’ => ‘post’));?>

<p>First Name: <?php echo Form::input(array(‘type’ => ‘text’, ‘name’ => ‘fname’));?></p>

<p>Last Name: <?php echo Form::input(array(‘type’ => ‘text’, ‘name’ => ‘lname’));?></p>

<p>Email: <?php echo Form::input(array(‘type’ => ‘text’, ‘name’ => ‘email’));?></p>

<p><?php echo Form::input(array(‘type’ => ‘submit’, ‘name’ => ‘send’, ‘value’ => ‘Create user’));?></p>

<?php echo Form::close();?>

</body>

</html>

This is it. At this point, you can see that building a basic database-driven application by using the sample MVC framework is indeed a no-brainer process that can be tackled with minor hassles. Of course, the functionality of each of its components can easily be enhanced, so go ahead and do it. It’ll be a good exercise for sharpening your programming skills.

Final thoughts

In this penultimate chapter of the series, I finished building a MySQL-driven application that used the functionality of the framework to perform CRUD operations on a database table populated with user-related data.

Even though it’s pretty basic, this example demonstrated how easy it is to build applications like the one mentioned above by simply reusing the framework’s components. And speaking of components, the only one that remains unused is the Cache class. So, in the last tutorial I’m going to show you how to use this class within the earlier sample application to cache database result sets, thus improving its performance.

Don’t miss the final part!

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