Creating a Templating System Using Object Oriented Programming

on Thu Nov 20 10:17:15 GMT 2008 in PHP and viewed 17808 times

When building a website, things can get a bit complicated with code written inside the template. A templating system serves to separate the structure (HTML) from the style (CSS) from the code/content (PHP and database) with PHP’s object oriented programming functions.


Fun fact: I used to code my websites in PHP, using MySQL to store content, and coding pretty sloppily. Unfortunately, it seems a lot of people do that as well. But luckily I found a much better way of creating web pages with PHP. Instead of the usual code inserted into where the content would go in a layout, it was much less tedious and more efficient to instead create an overall Template manager and class to manage the templates I wanted as needed. That way, through only a couple of commands, I could easily set up the layout I wanted with the content I wanted and customized the best. And now you can too.

Outlining The Class and Database (or Enough With the Sales Pitch)

Now the whole point of this is to compile all the essentials of a layout. So you really need to think about what parts of the layout you need for both the database and the overall template class. So here would be your templates table:


CREATE TABLE `templates` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) default NULL,
  `stylesheet` text,
  `body` text,
  PRIMARY KEY  (`id`)
);

It’ll be a very basic templating system, yet good enough to serve any purpose. You have a name for the template (for admin purposes), the stylesheet (CSS), and the body (HTML). For the class, you don’t need many functions. Just enough to fetch the HTML and CSS from the database, and to display it. The area for the content will be defined in the template as a simple HTML tag, or <contentarea /> Remember that.

Save as template.php

<?php

class Template{

    var $content = "";
    var $title = "";
    var $keywords = "";
    var $description = "";
    var $layout = "";
    var $stylesheet = "";
    var $body = "";

    function Template($layout){
    }

    function DisplayHead(){
    }

    function DisplayBody(){
    }

    function Display(){
    }

}

?>

Four functions and only seven variables. Shouldn’t be too hard.

Display() will call both DisplayHead() and DisplayBody() to stitch the entire layout together. Template() is a constructor function. Constructor functions are called as soon as the class is instantiated or called and always have the same name as the class. Template will take one argument, which will be a string, telling the class which layout to find in the database.

The variables are very self-explanatory. They aren’t defined at the moment because later you will define them as you set up the information for your layout.

Displaying The Layout

To start with the whole layout, you should define Display() just to know where you’re going.


function Display(){
        echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
            <html lang="en-us">
            <head>';
        $this->DisplayHead();
        echo '</head>
        <body>';
        $this->DisplayBody();
        echo '</body>
        </html>';
}

When called from your actual page, this function will display the whole layout. You can see it starts with the Doctype Declaration. Just stick with good ol’ XHMTL 1.0 Strict. Then the <head></head> tags surround the DisplayHead() function which will display all the necessary head information. And the same goes for <body></body>.

Now a subset to explain $this–>Function(). $This refers to the class, in this case Template. The ->Function makes a call to a function. So saying $this–>DisplayHead() will call the function DisplayHead() in the current class. And for outside classes, $this is exchanged for the variable that the class is instantiated into, so if the class was $class, then to call the Display function would be $class–>Display().

The next function will be DisplayHead(). This function will need to display:

  1. The Title
  2. The Content Type
  3. The Keywords
  4. The Description
  5. The CSS

Luckily, it will be very easy.


function DisplayHead(){
        echo '<title>';
        echo $this->title;
        echo '</title>';
        echo '';
        echo '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />';
        echo '';
        echo '<meta name="DESCRIPTION" content="';
        echo $this->description;
        echo '" />';
        echo '';
        echo '<meta name="KEYWORDS" content="';
        echo $this->keywords;
        echo '" />';
        echo '';
        echo '<style type="text/css">';
        echo $this->stylesheet;
        echo '</style>';
}

This too, is a very straightforward function. DisplayHead() first echoes the title, then the content type, the description, keywords, and the stylesheet.

As was explained previously, $this->Function() will call a function. It can be used the same for variables. Instead of a function, just specify the name of the variable to either return or to modify.

The last Display function to display your function is DisplayBody():


function DisplayBody(){
        echo str_replace("<contentarea />", $this->content, $this->body);
}

Very simple function. All it does, is replace the <contentarea /> tag you’ll put inside your layout wherever your content will be and replaces it with the class variable $body which you define before you call the Display function in your actual page.

Now that you are able to display the layout, you need to have the HTML and CSS to display from the database.

The Template Function

The template function, or the constructor function, will be called as soon as the class is instantiated. This is done to cut down on the amount of code needed in each page for your website and for ease (though I guess they go hand in hand).


function Template($layout){
        $connection = mysql_connect("localhost",
                            "username",
                            "password");
        mysql_select_db("database", $connection);
        $query = mysql_query("SELECT stylesheet, body FROM templates WHERE name = '$layout'") or die(mysql_error());
        $row = mysql_fetch_row($query);
        $this->stylesheet = $row[0];
        $this->body = $row[1];
}

Very easy class. First you need to connect to the database. Easy. Then fetch the information. Still easy. Then assign the class variables $stylesheet to $row0 and $body to $row1. What? Well, mysql_fetch_row() does what it says: it fetches the row from the query. That row then is assign to $row as an array. Arrays start at 0, and you selected stylesheet first, so that would logically be 0, and body would be 1. Then it assigns the class variables so that any other function (like DisplayHead and DisplayBody) can get to the CSS and HTML respectively.

Here’s the entire template class:


<?php

class Template{

    var $content = "";
    var $title = "";
    var $keywords = "";
    var $description = "";
    var $layout = "";
    var $stylesheet = "";
    var $body = "";

    function Template($layout){
        $connection = mysql_connect("localhost",
                            "username",
                            "password");
        mysql_select_db("database", $connection);
        $query = mysql_query("SELECT stylesheet, body FROM templates WHERE name = '$layout'") or die(mysql_error());
        $row = mysql_fetch_row($query);
        $this->stylesheet = $row[0];
        $this->body = $row[1];
    }

    function DisplayHead(){
        echo '<title>';
        echo $this->title;
        echo '</title>';
        echo '';
        echo '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />';
        echo '';
        echo '<meta name="DESCRIPTION" content="';
        echo $this->description;
        echo '" />';
        echo '';
        echo '<meta name="KEYWORDS" content="';
        echo $this->keywords;
        echo '" />';
        echo '';
        echo '<style type="text/css">';
        echo $this->stylesheet;
        echo '</style>';
    }

    function DisplayBody(){
        echo str_replace("<contentarea />", $this->content, $this->body);
    }

    function Display(){
        echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
            <html lang="en-us">
            <head>';
        $this->DisplayHead();
        echo '</head>
        <body>';
        $this->DisplayBody();
        echo '</body>
        </html>';
    }

}

?>

Well, now your class is completed. You can now easily template your pages. If you manually insert information into the database. So instead of that, let’s just create a simple admin.php to manage the whole deal.

Administrating (izing) the Templates

Now that you have your template class, you need to be able to add and edit templates in the database easily. You can do this with some mysql queries, html, and a switch().

First things first, you need a connection and a default case:


<?php
    $connection = mysql_connect("localhost",
                            "username",
                            "password");
        mysql_select_db("database", $connection);

    switch($_GET['act']){
        default:
            echo "<h1>Template Admin</h1>";
            echo "<h2>Listing Templates</h2>";
            echo "<table>";
            $select = mysql_query("SELECT * FROM templates") or die(mysql_error());
            while($r = mysql_fetch_array($select)){
                extract($r);
                echo "<tr>";
                echo "<td>$name</td>";
                echo "<td><a href='admin.php?act=edit&id=$id'>Edit Template</a></td>";
                echo "<td><a href='admin.php?act=delete&id=$id'>Delete Template</a></td>";
                echo "</tr>";
            }
            echo "</table>";
            echo "<h2>Add A New Template</h2>";
            ?>
            <form action="admin.php?act=new" method="post">
            <b>Name:</b><br />
            <input type="text" name="name" /><br />
            <b>Stylesheet:</b><br />
            <textarea name="stylesheet" rows="20" cols="60"></textarea><br />
            <b>Body:</b><br />
            <textarea name="body" rows="20" cols="60"></textarea><br />
            <input type="submit" value="Add New Template" />
            </form>
            <?
        break;
}
?>

It’s not that complex. There’s a simple MySQL connection to start. Then the case to display depends on the act variable in the url.

The default case is very simple. It selects all the templates, then loops throught them with mysql_fetch_array and a while loop and outputs each template’s name, an edit link, and a delete link into a table. There’s also a very simple form for you to add a template quickly.

Adding a Template

Here’s the code for processing the added template from the main page.


case "new":
   foreach($_POST as $variable){
     $$variable = $_POST['$variable'];
   }
   if(mysql_query("INSERT INTO templates VALUES('', '$name', '$stylesheet', '$body')") or die(mysql_error())){
     echo "Template added!";
     echo "<a href='admin.php'>Back to Admin for Templates</a>";
   }
   else {
    echo "Mysql Failure....";
   }
break;

The first loop is a bit odd (I admit I didn’t think it’d work) but it works. What it does is take the $_POST array (which contains each of the previous fields from the form and makes them their own variable for ease. $$variable basically says well, make the name of $variable into a variable itself and it assigns it to $variable’s value in the $_POST array. Then it’s just a matter of inserting the row into the database. Very simple.

Editing a Template

There are two steps to editing the template. The first is the form, the second would be the updating case. So to start, you need to see the template to edit it:


                case "edit":
            $id = $_GET['id'];
            $select = mysql_query("SELECT * FROM templates WHERE id = $id") or die(mysql_error());
            $row = mysql_fetch_row($select);
            ?>
            <form action="admin.php?act=edit2&id=<?=$row[0]?>" method="post">
            <b>Name:</b><br />
            <input type="text" name="name" value="<?=$row[1]?>" /><br />
            <b>Stylesheet:</b><br />
            <textarea name="stylesheet" rows="20" cols="60"><?=$row[2]?></textarea><br />
            <b>Body:</b><br />
            <textarea name="body" rows="20" cols="60"><?=$row[3]?></textarea><br />
            <input type="submit" value="Edit Template" />
            </form>
            <?
        break;

Not a particularly hard action. First the id is assigned to the value of id in the url. Then that row is selected and the result fetched.

The next thing to do would be to set up the form with the value of id in the action. The rest of the form is the same as adding the template in the first place, but with the added value attribute (for <input>. <textarea> has the value in between the tags) to display each value in the fields.

Next would be the case “edit2” according to the form up there. So without further ado:


                case "edit2":
            foreach($_POST as $variable){
                          $$variable = $_POST['$variable'];
                        }
            $id = $_GET['id'];
            if(mysql_query("UPDATE templates SET name = '$name', stylesheet = '$stylesheet', body = '$body' WHERE id = $id") 
                or die(mysql_error())){
                echo "Updated template";
                echo "<a href='admin.php'>Back to Admin for Templates</a>";
            }
            else {
                echo "Not updated.";
            }
        break;

All in all, self-explanatory. Using the same function foreach from before, each $_POST variable is given its own name. Then it’s just a matter of updating the certain row using the UPDATE [table] SET mysql command.

Last To Do: Deleting

Deleting is one of those things where it’s just tiring to do because you’ve written it so many times. Oh well, it’s needed just in case you’re tight on database space or if you just need to be organized.


               case "delete":
            if(mysql_query("DELETE FROM templates WHERE id = "+$_GET['id']) or die(mysql_error())){
                echo "Template annihilated!";
                echo "<a href='admin.php'>Back to Admin for Templates</a>";
            }
            else{
                echo "Could not delete...";
            }
        break;

All it is is one big if statement. If you can DELETE FROM templates where the id is the value of $_GET[‘id’] then say that the template was annihilated! Otherwise, tell us what the problem is.

Admin Conclusion

Looking back at the whole admin.php…


<html>
<head>
<title>Administration for Templates</title>
<script type="text/css">
textarea { width:350px; height:200px; }
</script>
</head>
<body>
<?php
    $connection = mysql_connect("localhost",
                            "username",
                            "password");
        mysql_select_db("database", $connection);

    switch($_GET['act']){
        default:
            echo "<h1>Template Admin</h1>";
            echo "<h2>Listing Templates</h2>";
            echo "<table>";
            $select = mysql_query("SELECT * FROM templates") or die(mysql_error());
            while($r = mysql_fetch_array($select)){
                extract($r);
                echo "<tr>";
                echo "<td>$name</td>";
                echo "<td><a href='admin.php?act=edit&id=$id'>Edit Template</a></td>";
                echo "<td><a href='admin.php?act=delete&id=$id'>Delete Template</a></td>";
                echo "</tr>";
            }
            echo "</table>";
            echo "<h2>Add A New Template</h2>";
            ?>
            <form action="admin.php?act=new" method="post">
            <b>Name:</b><br />
            <input type="text" name="name" /><br />
            <b>Stylesheet:</b><br />
            <textarea name="stylesheet" rows="20" cols="60"></textarea><br />
            <b>Body:</b><br />
            <textarea name="body" rows="20" cols="60"></textarea><br />
            <input type="submit" value="Add New Template" />
            </form>
            <?
        break;

        case "edit":
            $id = $_GET['id'];
            $select = mysql_query("SELECT * FROM templates WHERE id = $id") or die(mysql_error());
            $row = mysql_fetch_row($select);
            ?>
            <form action="admin.php?act=edit2&id=<?=$row[0]?>" method="post">
            <b>Name:</b><br />
            <input type="text" name="name" value="<?=$row[1]?>" /><br />
            <b>Stylesheet:</b><br />
            <textarea name="stylesheet" rows="20" cols="60"><?=$row[2]?></textarea><br />
            <b>Body:</b><br />
            <textarea name="body" rows="20" cols="60"><?=$row[3]?></textarea><br />
            <input type="submit" value="Edit Template" />
            </form>
            <?
        break;

        case "edit2":
                        foreach($_POST as $variable){
                $$variable = $_POST['$variable'];
            }
            $id = $_GET['id'];
            if(mysql_query("UPDATE templates SET name = '$name', stylesheet = '$stylesheet', body = '$body' WHERE id = $id") 
                or die(mysql_error())){
                echo "Updated template";
                echo "<a href='admin.php'>Back to Admin for Templates</a>";
            }
            else {
                echo "Not updated.";
            }
        break;

        case "delete":
            if(mysql_query("DELETE FROM templates WHERE id = "+$_GET['id']) or die(mysql_error())){
                echo "Template annihilated!";
                echo "<a href='admin.php'>Back to Admin for Templates</a>";
            }
            else{
                echo "Could not delete...";
            }
        break;

        case "new":
            foreach($_POST as $variable){
                $$variable = $_POST['$variable'];
            }
            if(mysql_query("INSERT INTO templates VALUES('', '$name', '$stylesheet', '$body')") or die(mysql_error())){
                echo "Template added!";
                echo "<a href='admin.php'>Back to Admin for Templates</a>";
            }
            else {
                echo "Mysql Failure....";
            }
        break;
    }

?>
</body>
</html>

Very simple CRUD (Create Read Update Delete). You know, PHP needs a scaffolding command…

Anyways that’s done. Just add a template now. This was my example:

Name: two columns

Stylesheet:


* { margin:0; padding:0; }

p { margin:auto; padding:2px; }

BODY { font-family:"Trebuchet MS", Verdana, Arial, sans-serif; 

    font-size:12px;

    line-height:160%; }

ul li {

  font-size: 12px;

  list-style: none;

}

textarea { margin:2px; padding:.2em; }

input { margin:2px; padding:.2em; width:190px; }

pre {

  background-color: #eee;

  padding: 10px;

  font-size: 11px;

}

/*** headers and links ***/

a { color:#507EA1; }

a img { border:0; }

h1 { color:#CFDCE6;

    font-size:150%; }

h1 a { color:#CFDCE6; }

/*** page elements ***/

#header { background-color:#596F80;

    border-bottom:5px solid #6096BF;

    padding:1em;

    padding-left:2em; }

#navigation { background-color:#647D8F;

    padding:1em; }

#navigation li { display:inline;

    padding-right:1em; }

#navigation li a { color:#CFDCE6;

    font-size:150%; }

#navigation li a:hover { background-color:#50A17E;

    color:#CFE6DC;

    padding:.5em;

    border:1px solid #596F80; }

#doublebar { height:20px;

    background-color:#CCC08F;

    border-bottom:7px solid #BFAC60;

    padding:.3em; }

#doublebar h1 { font-size:15px;

    margin-left:10px;

    color:#000; }

#leftside {    padding:.5em;

    width:24%;

    margin-left:1%; }

#leftside a img { border:0; }

#searchresults { background-color:#CFDCE6;

    border:1px solid #596F80; /* solid kryptonite */

    padding:.3em; }

#rightside { float:right;

    width:73%;

    margin-left:-5%; }

#social li { display:inline; }

#reviewnav { background-color:#647D8F;

    padding:.5em;

    border:2px solid #CCAE8F; }

#reviewnav li { display:inline;

    font-size:18px;

    padding:1em; }

#reviewnav a { color:#CFDCE6; }

.article { border-bottom:1px #9B9B5F dotted;

    margin-bottom:1em;

    padding:.5em; }

.comment { border-bottom:1px #9B9B5F dotted;

    margin-bottom:1em;

    padding:.5em;

    width:75%; }

#rightside h1 { margin-bottom:.5em; }

.notbox { border-top:1px #9B9B5F dotted;

    padding:.3em 0 .3em 0;

    margin-top:5px; }

#footer { clear:both;

    padding:.5em;

    background-color:#647D8F;

    border-top:3px solid #6A9777;

    color:#FFF;

    margin-top:7em; }

#footer a { color:#CFDCE6; }

#footnav { float:left;

    padding:.5em;

    width:47%; }

#siteabout { margin-left:49%;

    padding:.5em; }

Body:


<div id="header">
<h1>
<a href="http://www.shadow-fox.net">The Shadow Fox Network - Ruby on Rails, PHP, XHTML, CSS, Javascript, and XML Tutorials</a>
</h1>
</div>

<ul id="navigation">
<li><a href="/site/tutorials/PHP">PHP</a></li>
<li><a href="/site/tutorials/XHTML-and-CSS">XHTML/CSS</a></li>
<li><a href="/site/tutorials/Javascript">Javascript</a></li>
<li><a href="/site/tutorials/Ruby-on-Rails">Ruby on Rails</a></li>

<li><a href="/site/tutorials/XML">XML</a></li>
<li><a href="/site/tutorials/Webmaster-Articles">Webmaster Articles</a></li>
<li><a href="/site/reviews/all">Reviews</a></li>
</ul>
<!--end-->

<!--start content-->

<div id="rightside">
<contentarea />
</div>
<!--end content-->

<!--the left side-->
<div id="leftside">

<!--header image-->
<a href="http://www.shadow-fox.net">
<img src="/images/header.gif" width="200" height="160" alt="Ruby on Rails, Javascript, and web rantings in whammy bar form." />
</a>

<!--start search-->
<div class="notbox">
<h3>The Search Deal</h3>

<form action="/site/search" method="post">
<p>
<label for="search_search"><b>Search Term:</b></label><br />
<input alt="Search the Shadow Fox Network" id="search_search" name="search[search]" size="30" type="text" />
<input name="commit" type="submit" value="Search" />
</p>
</form>
<!--end search-->
</div>

<div class="notbox">

    Advertise here!

</div>

<div class="notbox">
<h3>About Ben</h3>
I'm 16 and I've been on the computer since I was 18 months old (and yes I have video). I love computers 
and music. I play trumpet in the school band and guitar for fun. I love anything on this subject of web 
programming. My walls are just covered in books. And I try to take some of my experiences programming 
and put it into tutorials here.<br />
<a href="/site/about">More About Me and The Site</a>
</div>

<!--start navigation-->

<div class="notbox">
<h3>Often Visited Resources</h3>
<ul>
<li>
<a href="http://feeds.feedburner.com/TheShadowFoxNetworkTutorialsFeed">
<img alt="Rss" src="/images/rss.gif?1152752802" />
</a> - Tutorial RSS Feed
</li>

    <li><a href="http://webdesignbook.net/approved/wwwshadow-foxnet/">Web Design Book Approved</a></li>

    <li><a href="http://www.my-tuts.com">My-Tuts</a></li>

    <li><a href="http://www.maxed-virtuals.com/">Maxed Virtuals</a></li>

    <li><a href="http://www.bhsdesign.com/">BHS Design</a></li>

    <li><a href="http://www.counterfrag.com/">Counter Frag</a></li>

    <li><a href="http://www.anigamenetwork.net/">The Anigame Network</a></li>

    <li><a href="http://www.photoshopdepot.com/">Photoshop Depot</a></li>

    <li><a href="http://www.greycobra.com">Greycobra</a></li>

    <li><a href="http://www.pixel2life.com/forums/index.php?act=toplist&code=hitin&site=211">Pixel2Life</a>
</li>

    <li><a href="http://www.stefashwell.com/">Stef Ashwell</a></li>

    <li><a href="http://www.totaltutorial.com/home/">Total Tutorial</a></li>

</ul>

</div>
<!--end navigation-->

<!--newstuff-->
<div class="notbox">
<h3>Newest Tutorials</h3>

    <a href="/site/tutorial/37-Building-Content-By-Parsing-RSS-Feeds-With-PHP">
Building Content By Parsing RSS Feeds With PHP
</a><br />

    <a href="/site/tutorial/36-Automatically-Saving-Drafts-Using-Periodically-Call-Remote">
Automatically Saving Drafts Using Periodically_Call_Remote
</a><br />

    <a href="/site/tutorial/35-Designing-Your-Very-Own-Web-2-Layout">
Designing Your Very Own Web 2.0 Layout
</a><br />

    <a href="/site/tutorial/34-Making-a-Two-Column-Fluid-Layout-With-Rounded-Corners">
Making a Two Column Fluid Layout With Rounded Corners
</a><br />

</div>

<div class="notbox">
<h3>Newest Reviews</h3>

    <a href="/site/review/1-Agile-Web-Development-with-Rails">
Agile Web Development with Rails
</a><br />

</div>

<!--/newstuff-->

</div>
<!--end the left side-->

<!--footer-->
<div id="footer">
<ul id="footnav">
<li><a href="http://www.shadow-fox.net">Home</a></li>
<li><a href="http://forum.shadow-fox.net">The Forums</a></li>
<li><a href="/site/tutorials/PHP">PHP</a></li>
<li><a href="/site/tutorials/XHTML-and-CSS">XHTML/CSS</a></li>
<li><a href="/site/tutorials/Javascript">Javascript</a></li>

<li><a href="/site/tutorials/XML">XML</a></li>
<li><a href="/site/tutorials/Ruby-on-Rails">Ruby On Rails</a></li>
<li><a href="/site/tutorials/Webmaster-Articles">Webmaster Articles</a></li>
<li><a href="/site/reviews/all">Reviews</a></li>
<li><a href="http://blog.shadow-fox.net">Ben's Blog</a></li>
</ul>

<div id="siteabout">
<ul>
<li>©2006 <a href="http://blog.shadow-fox.net">Ben Hirsch</a></li>

<li><a href="/site/about">About</a></li>
<li><a href="http://jigsaw.w3.org/css-validator/check/referer">CSS Valid</a></li>
<li><a href="http://validator.w3.org/check/referer">XHTML 1.0 Valid</a></li>
<li><a href="/site/about">Big List O' Feeds</a></li>
<li><a href="http://feeds.feedburner.com/TheShadowFoxNetworkTutorialsFeed">The Main Tutorial Feed</a></li>
</ul>
</div>

<br style="clear:both;" />
</div>
<!--end footer-->

The whole thing is pretty easy. It’s just my website’s layout. There might be some extra not needed stuff in the CSS area. Anyways, go ahead and add that for your first template!

The Actual Page

Well you have the groundwork laid for your page now. But you still have to actually display something, right? Right.

The code for displaying the page is downright puny compared to the class required to output it all. But the simplicity will be so much better for your web sites.


<?php
    include("template.php");

    $template = new Template('two columns');
    $template->title = "This is a two column layout";
    $template->keywords = "two columns, object oriented programming, template system, web pages with oop, php";
    $template->description = "This layout was made dynamically with PHP's Object Oriented Programming Capabilites";
    $template->content = "This is some content for the layout. Have fun with it.";
    $template->Display();
?>

Yeah, that’s pretty much it.

The first thing you need to do here is to include the class’s code. That’s a must. Then just instantiate the Template class into template using the new command. Also need is the argument of ‘two columns’ to tell the constructor function (remember?) to fetch the right name from your database.

Next is a bunch of variable setting. You can set the title to whatever you want, the keywords, the description the content, whatever. They’re all inserted dynamically into the page.

For your more dynamic applications, instead of just specifying content manually, you can have the page pull the content (keywords, title, whatever) from your database and assign it through the variable accessors like this. So much easier.

And of course the final function: Display(). That will string everything together and really paying everything off.

The Real Conclusion

Now you have your very own templating system. No more wasted hours of coding trying to insert all the content code into your layouts, or even with includes, whatever. It’s all done dynamically. All that’s needed is a few lines of code for the output and a minute or two of administration. Easy, even if you’re rehauling your backend.

Ideas For Extension

  1. Make all the titles have a tacked on “from Your Website Name” like this one
  2. Sanitize the database input and output.
  3. Extend the class for specific subpages that need something different
  4. Add a links section tag and use str_replace() to replace that in outputting the template

As always, go forth with your code and have fun.