Creating a Simple Template Engine with OO PHP.
Click here to download demo files
Ever try to apply a new look to your site and have to wade through all your pages updating the code? If you are creating a website that will have a number of pages it is important to utilize a template engine. A template engine enables you to roll out an entirely new layout or fix a bug without having to manually apply the changes to all of your pages.
File Structure

Step 1: Create the Page Class
Here we declare a standard class with a few properties and a constructor method.
<?php
class Page {
private $title, $stylesheets=array(), $javascripts=array(), $body;
function Page() {
}
}
For those not familiar with OOP, in classes variables are called properties and functions are called methods. Also, if there is a method that has the same name as the class or the name __construct() it will automatically be called when the class is instantiated.
Step 2: Create a Method to Set the Title
Now we create a method that copies the argument passed to the method into the title property.
function setTitle($title) {
$this->title = $title;
}
Step 3: Create a Method to Add CSS Stylesheets and Javascript
Both methods do the same thing. They take the argument passed to the method and append it to their respective arrays.
function addCSS($path) {
$this->stylesheets[] = $path;
}
function addJavascript($path) {
$this->javascripts[] = $path;
}
Step 4: Create a Method to Start and End Body Capture
Now we are going to create two methods: one that starts the capture of the html we want to use for the body of our page and one that stores it in the body property.
function startBody() {
ob_start();
}
ob_start() is a PHP function that stores output to a buffer instead of sending it to the user's browser. The documentation for ob_start() can be read here.
function endBody() {
$this->body = ob_get_clean();
}
ob_get_clean() is a PHP function that gets the contents of the buffer and then deletes the buffer. The documentation for ob_get_clean() can be read here.
If you're confused about what exactly this is doing, don't worry; it should make more sense later in the tutorial when we use it.
Step 5: Create a Method to Render the Page
This method takes in the path to the desired template file, includes it, and returns the "assembled" page.
function render($path) {
ob_start();
include($path);
return ob_get_clean();
}
Step 6: Quick Modification to Constructor Method
Right now our constructor method is empty. However if there are any stylesheets or scripts that you want added to every page you can declare them here. This is what we're going to do now.
function Page() {
$this->addCSS('css/main.css');
}
Now when you instantiate the page class your main stylesheet is automatically included. You could just include the stylesheet in your template file; however, it is my personal preference to have the page class handle everything.
At this point your Page.php file should look like this:
<?php
class Page {
private $title, $stylesheets=array(), $javascripts=array(), $body;
function Page() {
$this->addCSS('css/main.css');
}
function setTitle($title) {
$this->title = $title;
}
function addCSS($path) {
$this->stylesheets[] = $path;
}
function addJavascript($path) {
$this->javascripts[] = $path;
}
function startBody() {
ob_start();
}
function endBody() {
$this->body = ob_get_clean();
}
function render($path) {
ob_start();
include($path);
return ob_get_clean();
}
}
Step 7: Create a Template to Use
HTML Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>XYZ Company | <?php echo $this->title; ?></title>
<?php
foreach ($this->stylesheets as $stylesheet) {
echo '<link href="' . $stylesheet . '" rel="stylesheet" type="text/css" />' . "\n";
}
?>
</head>
<body>
<div align="center"><div class="container">
<div id="header">
<span id="cname">XYZ Company</span>
<ul id="nav">
<li><a href="index.php">Home</a></li>
<li><a href="about.php">About Us</a></li>
<li><a href="services.php">Services</a></li>
<li><a href="contact.php">Contact Us</a></li>
</ul>
</div>
<img src="images/blockimage.jpg" alt="Block Image" />
<?php echo $this->body; ?>
<div id="cpyright">© Copyright 2008 XYZ Company. All rights reserved.</div>
</div></div>
<?php
foreach ($this->javascripts as $javascript) {
echo '<script src="' . $javascript . '" language="javascript" type="text/javascript" defer="defer"></script>' . "\n";
}
?>
</body>
</html>
This should be pretty straight forward. Here we put any HTML that should be on every page that calls this template. We then use php echo commands to fill in the information that is unique to each page and foreach statements to iterate through any arrays.
CSS Code:
body {
font:13px Arial, Helvetica, sans-serif;
color:#333;
line-height:18px;
margin:0px;
padding:0px;
border-top:8px solid #333;
}
/* Layout------------------------------------------------ */
.container {
width:960px;
text-align:left;
position:relative;
}
#header {
margin:8px 0px;
padding:8px 0px;
border-bottom:1px solid #d0d0d0;
}
#nav {
position:absolute;
top:0px;
right:0px;
display:inline;
}
#cpyright {
border-top:1px solid #d0d0d0;
color:#d0d0d0;
}
/* Links------------------------------------------------ */
a {
color:#333;
text-decoration:none;
}
a:hover {
color:#777;
}
/* Text------------------------------------------------ */
#cname {
color:#ccc;
font-size:2.8em;
font-weight:bold;
}
h2 {
color:#a3c2bd;
font-size:1.8em;
}
/* Forms------------------------------------------------ */
#searchquery {
background-color:#eee;
border:1px solid #ddd;
padding:2px;
color:#777;
}
/* Nav------------------------------------------------ */
ul#nav li {
list-style:none;
float:left;
margin:0px;
padding:8px;
font-size:14px;
font-weight:bold;
}
/* Tables------------------------------------------------ */
form th {
text-align:right;
border-right:1px solid #ccc;
padding:4px 8px 4px 0px;
vertical-align:top;
}
form td {
padding:4px 0px 4px 8px;
vertical-align:top;
}
Step 8: Putting Everything Together
Now it's time to use what we've created. Here is how we would create the home page pictured below:

<?php
require_once('libraries/Page.php');
$page = new Page;
$page->setTitle('Home');
$page->startBody();
?>
<h2>Home</h2>
<p>Lorem ipsum dolor sit amet, consectetur...</p>
<?php
$page->endBody();
echo $page->render('inc/template.php');
We import our Page class and create a new instance which we store in the variable "page". We can then call the various methods we've created to set the title, add a stylesheet, or add an external javascript. Next we call the startBody method which stores all the HTML we output into a buffer until we call the endBody method. We finish things up by calling the render method — passing the path of the template we want to use as an argument.
Congratulations. You're Done!
As you can see from this tutorial making a custom template engine for your site is quite simple. To finish things up here is a general overview of what is going on at each step. Hopefully this will help clarify anything you may be confused about.

Thanks for reading. I hope you've found this tutorial useful and will put what you've learned to use. The best way to learn is to play around; so try and write some additional methods to make your template engine even more robust.
