Templating
There is a common problem in PHP of business logic and codesentation being combined to closely. To get around this templating can
be used.
Templating is where the page structure is seperated from the business logic.
The Template
Below is a simple template which displays a list of users. This will be saved as user_template.php.
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<h1>Users</h1>
<?php
foreach($users as $user)
{
echo $user->username;
}
?;>
</body>
</html>
The Class
This class handles the bussiness logic, and calls the template.
class User
{
private function getUsers()
{
.
.
.
}
public function showUsers()
{
$title = "User list";
$users = $this->getUsers();
include("user_template.php");
}
}
As you can see the showUsers function sets the title variable for the template and the users variable
to display by setting the title and users variables, which the user_template.php file then displays by echoing the values to the screen.
The advantage of this is that a change to the template doesn't mean the User class has to change.
This has many advantages especially for small websites however a better solution for larger systems would be the MVC pattern,
which we will discuss in a later tutorial.
No comments have been provided.
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38