TUTORIAL: Basic PHP Templating mechanism

  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

Basic PHP Templating mechanism



Having seen many embedded html strings in PHP functions I thought it would be helpful to illustrate a really simple straight forward way of implementing a templating engine. This tutorial is broken into 4 sections namely
1) Requirements
2) System Design (UML)
3) Implementation
4) Usage of implementation

Requirements


1) Fully functional HTTP server including PHP binaries for that server
2) Text Editor
3) Web browser capable of rendering the content

System Design


Attachments:
TutorialClassModel.gif


Description:
css = our css file for the template
isValid = unused in this tutorial but might be useful once you get the hang of this to check if the template is valid based on what ever criteria you decide (file location invalid, something not define etc etc)
templateDir = the path to and including the directory containg our template
TemplateDir() = our constructor
display(file) = the file to display in our template

Implementation


Lets define our constructor
Code: [ Select ]
 
 
function Template(){
  $this->templateDir = "default";
  $this->css = "default.css";
}
 
  1.  
  2.  
  3. function Template(){
  4.   $this->templateDir = "default";
  5.   $this->css = "default.css";
  6. }
  7.  


Here we define the template dir as "default" which means this, if you are working on file home/mypage.php and including the template file from there, the path to the directory containing th info will be home/default/. So in other words the folder will be relative to the path of the calling file. Next we define the stylesheet as default.css which means the path is home/default/default.css. Understand? Great lets move on then

Code: [ Select ]
 
function display($file){
  $template = $this;
  error_reporting(E_ALL);
  include_once("template/" . $this->templateDir ."/".$file);
}
 
  1.  
  2. function display($file){
  3.   $template = $this;
  4.   error_reporting(E_ALL);
  5.   include_once("template/" . $this->templateDir ."/".$file);
  6. }
  7.  


Here we set the error reporting level, you might at a later stage want to define some sort of flag that changes the reporting level to suit the environment, like production or development instance. then we include the file according to the directory we specified in the constructor. this path has template prefixing it as I prefer to store my templates in a directory called templates (funny that). So the path would be home/templates/default.

The class in all its glory below
Code: [ Select ]
 
<?php
 
class Template{
 
  var $templateDir;
  var $css;
  var $isValid;
 
  function Template(){
    $this->templateDir  = "default";
    $this->css = "default.css";
  }
  function display($file){
    $template = $this;
    error_reporting(E_ALL);
    include_once("template/" . $this->templateDir ."/".$file);
  }
}
 
?>
 
  1.  
  2. <?php
  3.  
  4. class Template{
  5.  
  6.   var $templateDir;
  7.   var $css;
  8.   var $isValid;
  9.  
  10.   function Template(){
  11.     $this->templateDir  = "default";
  12.     $this->css = "default.css";
  13.   }
  14.   function display($file){
  15.     $template = $this;
  16.     error_reporting(E_ALL);
  17.     include_once("template/" . $this->templateDir ."/".$file);
  18.   }
  19. }
  20.  
  21. ?>
  22.  


Right everyone with me so far? Great lets define some templates

header.tpl (inside the default folder)
Code: [ Select ]
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>My Template :: <?php echo $template->title; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="template/<?php echo $template->templateDir . "/default.css" ?>" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
My Template header <?php echo $template->welcome; ?>
</div>
 
  1.  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  3. <html>
  4. <head>
  5. <title>My Template :: <?php echo $template->title; ?></title>
  6. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  7. <link href="template/<?php echo $template->templateDir . "/default.css" ?>" rel="stylesheet" type="text/css" />
  8. </head>
  9. <body>
  10. <div>
  11. My Template header <?php echo $template->welcome; ?>
  12. </div>
  13.  


There we go, save the file and lets proceed to home.tpl in the same directory
Code: [ Select ]
 
<div>
Well hello there <?php echo $template->name; ?><br />
I am so glad you could join me on my <?php echo $template->content; ?><br />
Look here, I have put your name in a textbox <input type='text' id="txtMyName" value="<?php echo $template->name; ?>" /><br />
have a happy day!
</div>
</body>
 
  1.  
  2. <div>
  3. Well hello there <?php echo $template->name; ?><br />
  4. I am so glad you could join me on my <?php echo $template->content; ?><br />
  5. Look here, I have put your name in a textbox <input type='text' id="txtMyName" value="<?php echo $template->name; ?>" /><br />
  6. have a happy day!
  7. </div>
  8. </body>
  9.  


Cool so now our implementation is done! I have included the text box so you can see that this can be used in data entry forms when editing data.

Usage


Well I bet you itching to see this right? well even if you not I am going to show you anyway :P

Lets assume our php page is called mypage.php.

First thing we do is include the template class

Code: [ Select ]
 
include_once("lib/Template.class.php") // I have saved the template class we added into a dir called lib as file name Template.class.php
 
  1.  
  2. include_once("lib/Template.class.php") // I have saved the template class we added into a dir called lib as file name Template.class.php
  3.  


Next thing we do is create a reference to the Template object (for those that have worked with classes the correct term is instantiate an instance Template class)

Code: [ Select ]
 
$oTemplate = new Template();
 
  1.  
  2. $oTemplate = new Template();
  3.  


Right, now we need to populate the variables in the page
Code: [ Select ]
 
$oTemplate->title = "Check out my template page!";
$oTemplate->welcome = "Howdy doody!";
$oTemplate->name = "Captain Cheese Monkey";
$oTemplate->content = "Here I can put all my html content, whether it be a read from a file or dynamically created content from my super DB";
 
  1.  
  2. $oTemplate->title = "Check out my template page!";
  3. $oTemplate->welcome = "Howdy doody!";
  4. $oTemplate->name = "Captain Cheese Monkey";
  5. $oTemplate->content = "Here I can put all my html content, whether it be a read from a file or dynamically created content from my super DB";
  6.  


And we all done! Here is the complete page
mypage.php
Code: [ Select ]
 
<?php
include_once("lib/Template.class.php");
 
$oTemplate->title = "Check out my template page!";
$oTemplate->welcome = "Howdy doody!";
$oTemplate->name = "Captain Cheese Monkey";
$oTemplate->content = "Here I can put all my html content, whether it be a read from a file or dynamically created content from my super DB";
 
$oTemplate->display("header.tpl");
$oTemplate->display("home.tpl");
?>
 
  1.  
  2. <?php
  3. include_once("lib/Template.class.php");
  4.  
  5. $oTemplate->title = "Check out my template page!";
  6. $oTemplate->welcome = "Howdy doody!";
  7. $oTemplate->name = "Captain Cheese Monkey";
  8. $oTemplate->content = "Here I can put all my html content, whether it be a read from a file or dynamically created content from my super DB";
  9.  
  10. $oTemplate->display("header.tpl");
  11. $oTemplate->display("home.tpl");
  12. ?>
  13.  


And that as they say in the classics is that. Nice clean and simple. You can extend this from here to the four corners of the planet (it is flat right?) and enjoy time doing the fun things like coding logic as opposed to coding html strings!

Conclusion


This is an extremely simple example designed to get you up and running fast. This is by no means a comprehensive solution but is aimed at helping you understand how to seperate the logic from your view and how to create nice clean models which allow for easy maintenance and content reusage.

Rabid Dog out.
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6254
  • Loc: Seattle, WA

Post 3+ Months Ago

Fee fye foh fum... I see Hungarian notation in there!
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

lol yeah only way I can differentiate objects in PHP ;)
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

spork wrote:
Fee fye foh fum... I see Hungarian notation in there!


Besides in a duck typed language it is the only way to clearly see what the object is LOL. I do however appreciate the fact that you picked it up, had a good chuckle when I read your comment. Made the tutorial worth while.
  • SpooF
  • ٩๏̯͡๏۶
  • Bronze Member
  • User avatar
  • Posts: 3422
  • Loc: Richland, WA

Post 3+ Months Ago

Rabid Dog, whats your take on systems like smarty? When should they be used? I've been in a lot of discussion over systems like smarty and something simple like what you have here.
  • UPSGuy
  • Lurker ಠ_ಠ
  • Web Master
  • User avatar
  • Posts: 2733
  • Loc: Nashville, TN

Post 3+ Months Ago

SpooF - I know you didn't ask me, but I'll give my two cents anyways. :D I've built a half-dozen or so projects using Smarty & I've spent the last year or so of my career customizing three separate installations of SugarCRM, which also implements Smarty.

IMHO, the Smarty engine is great for large applications where a cache may come in handy. Our CRM systems get hit several hundred times an hour, serving up a large header and menu with each hit, so the caching is a benefit for us. I also like the external configuration files that you can implement. If you need to migrate between dev/QA/prod environments or between systems, then having all your configuration in one place is a great way to smooth transitions. Those stand out in my mind as the features I most use in Smarty, but there's also a few that I've used here and there when necessary such as filtering and template functions. Of course, compiled templates are always a benefit, too.

All that being said, there's a place for sweet and simple, too. A templating system like what Rabid Dog has provided would definitely be my choice over Smarty for smaller projects. Smarty performs surprisingly well given all of its capabilities, but it can also overwhelm a project.
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

SpooF wrote:
Rabid Dog, whats your take on systems like smarty? When should they be used? I've been in a lot of discussion over systems like smarty and something simple like what you have here.

My opinion on smarty is this.

It is a created framework so it probably contains a great deal of useful stuff. The only thing I have against it is just that, it is a framework with a lot of stuff in it :)

This simple templating solution has allowed me to create a number of sites and works quiet nicely. The other thing is the learning curve. This you write it so you can extend it as needed. So only when you need the extensions put them in, not before :)

Again I must stress I have nothing against smarty but prefer the absolute control I get out of writing my own :)

Make sense?
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6254
  • Loc: Seattle, WA

Post 3+ Months Ago

Code: [ Select ]
function display($file){
  $template = $this;
  error_reporting(E_ALL);
  include_once("template/" . $this->TemplateDir ."/".$file);
}
  1. function display($file){
  2.   $template = $this;
  3.   error_reporting(E_ALL);
  4.   include_once("template/" . $this->TemplateDir ."/".$file);
  5. }


What purpose does the blue line above serve? It looks like all you're doing is creating a copy of your self reference but not using it.
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

It is a quirky in PHP.

I will do some tests for you so I can clarify it completely
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8416
  • Loc: USA

Post 3+ Months Ago

spork wrote:
Code: [ Select ]
function display($file){
  $template = $this;
  error_reporting(E_ALL);
  include_once("template/" . $this->TemplateDir ."/".$file);
}
  1. function display($file){
  2.   $template = $this;
  3.   error_reporting(E_ALL);
  4.   include_once("template/" . $this->TemplateDir ."/".$file);
  5. }


What purpose does the blue line above serve? It looks like all you're doing is creating a copy of your self reference but not using it.

He is using it... look at the HTML part of the template example... I actually understand half of it... (The 'what for' part... not the why :lol: )
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

Yes spot on :) the $template variable is available when called inside the template (.tpl) page. As to why? Well when the file is included it is included in the context of the function therefore the $template variable is available inside the included page :) Allowing you to assign values to it via the $oTemplate variable.

Make sense?
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6254
  • Loc: Seattle, WA

Post 3+ Months Ago

Ah I see now. Sneaky.
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8416
  • Loc: USA

Post 3+ Months Ago

Rabid Dog wrote:
Yes spot on :) the $template variable is available when called inside the template (.tpl) page. As to why? Well when the file is included it is included in the context of the function therefore the $template variable is available inside the included page :) Allowing you to assign values to it via the $oTemplate variable.

Make sense?

I thought there was a more technical reason :shock:
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

Well it is technical. Remove the assignment of $this to the $template variable and see what happens ;)

Post Information

  • Total Posts in this topic: 14 posts
  • Moderator: Tutorial Writers
  • Users browsing this forum: No registered users and 1 guest
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
cron
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.