WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Poker Tournaments Poker Tournaments
Poker Guide for Developers Poker Guide for Developers
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
Internet Security Software
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
פרייסז - הכח לקנות עובר לידיים שלך
Texas Holdem Poker Evangelists

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : Object Oriented Templating using PHP
Categories : PHP, PHP Classes, Templates Click here to Update Your Picture
Vinod Mohan
Date : Dec 31st 2008
Grade : 2 of 5 (graded 4 times)
Viewed : 7836
File : No file for this code example.
Images : No Images for this code example.
Search : More code by Vinod Mohan
Action : Grade This Code Example
Tools : My Examples List

Submit your own code examples  Submit your own code examples 
 

This is the templating system that I currently use on my site. Ofcourse, I make small changes to make it suit my sites.

Save as class.template.php
<?php

class Template{
    private
$cache = false;
    private
$cacheKey = NULL;
    private
$cachePeriod = 3600;
    private
$cachePath = NULL;
    private
$tplFile = NULL;
   
    function
enableCaching($key = NULL, $ttl = 3600){
       
$this->cache = true;
        if(!
is_null($key)){
           
$this->cacheKey = $key;
        }
       
$this->cachePeriod = $ttl;
    }
   
    function
disableCaching(){
       
$this->cache = false;   
    }
   
    function
setCachePath($path){
       
$this->cachePath = $path;   
    }
   
    function
getCacheFile(){
        if(
is_null($this->cachePath) || !file_exists($this->cachePath)){
           
$this->error('Invalid Cache Path.');   
        }
       
$cacheKey = is_null($this->cacheKey) ? md5($this->tplFile) : $this->cacheKey;
        return
$this->cachePath . '/' . $cacheKey;
    }
   
    function
cacheExist(){
       
$cacheFile = $this->getCacheFile();
        if(
file_exists($cacheFile) && filemtime($cacheFile) > time() - $this->cachePeriod){
            return
true;
        }else{
            return
false;
        }
    }
   
    function
getCache(){
        if(
$this->cache && $this->cacheExist()){
            echo
file_get_contents($this->getCacheFile());
            return
true;
        }else{
            return
false;
        }
    }
   
    function
setTemplate($tpl){
       
$this->tplFile = $tpl;
    }
   
    function
generate(){
        if(!
file_exists($this->tplFile)){
           
$this->error("Template File <i>$this->tplFile</i> not found.");
        }
       
extract(get_object_vars($this), EXTR_REFS | EXTR_PREFIX_ALL, 't');
        if(
$this->cache){
           
$cacheFile = $this->getCacheFile();
           
ob_start();
            include
$this->tplFile;
           
$output = ob_get_clean();
           
file_put_contents($cacheFile, $output);
            echo
$output;
        }else{
            include
$this->tplFile;
        }

    }
    function
error($message = ''){
        if(empty(
$message))$message = 'A fatal error occured. Unable to continue.';
        die(
"<b>Error</b> : $message");
    }
   
}
?>


Run the following query using phpMyAdmin to setup the database for the example script
--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(5) unsigned NOT NULL auto_increment,
  `name` varchar(25) NOT NULL,
  `email` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'Lord Beckett', 'lord@beckett.com'),
(2, 'Davy Jones', 'davy@jones.com'),
(3, 'Jack Sparrow', 'jack@sparrow.com'),
(4, 'Will Turner', 'will@turner.com');


Example template file. Save as template.tpl.php. It is better to make sure that the filename ends in .php, so that it can make use of opcode caches like eaccelerator.
<html>
<head>
<title><?=$t_title?></title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h1><?=$t_h1?></h1>
<table border="1">
<tr><td>ID</td><td>Name</td><td>Email</td></tr>
<?php foreach($t_users as $user):?>
<tr><td><?=$user['id']?></td><td><?=$user['name']?></td><td><?=$user['email']?></td></tr>
<?php endforeach;?>
</table>
</body>
</html>


Example script. Save as example.php in the same directory as the class.template.php
<?php
include 'class.template.php';
$tpl = new Template;
$tpl->setTemplate('template.tpl.php');
$tpl->enableCaching();
// Change the path to your cache path
$tpl->setCachePath('/var/www/vhosts/mysite.com/httpdocs/cache/');

if(
$tpl->getCache()){
    echo
'This was loaded from cache.';
}else{
    if(
mysql_connect('localhost', 'root', '')){
       
// Add variables to the template object as you like.
        // You can access these variables in the template file by prefixing it with t_. For example $tpl->h1 becomes $t_h1, $tpl->users becomes $t_users.
       
$tpl->title = 'My Template Example';
       
$tpl->h1 = 'Example';
       
mysql_select_db('test');
       
$result = mysql_query("SELECT * FROM `users`");
        while(
$row = mysql_fetch_assoc($result)){
           
$tpl->users[] = $row;   
        }
    }else{
       
$tpl->error('Could not connect to mysql');   
    }
   
$tpl->generate();
    echo
'This content will be saved to cache';
}

?>



Parsing Simple Template Files and Data
Categories : PHP, PHP Classes, Templates, Regexps
Very minimal templating engine
Categories : PHP, PHP Classes, Templates
Expose - PHP template engine, supports server and client-sided caching,a plugin system, multiple languages, template script language is based on PHP itself.
Categories : PHP, PHP Classes, Templates, Complete Programs
Simple Template Class/Example
Categories : PHP, Templates, PHP Classes
Sort the results from a SELECT query (any number of columns) into an array automatically.
Categories : PHP, PHP Classes, Arrays, Databases, MySQL
usercounter class
Categories : PHP, PHP Classes, Databases, MySQL, Environment Variables
Most of the browsers, especially Internet Explorer, behave in different ways. Hence it become necessary to use Browser detection to fix the non standard behavior of the browser. This is a browser sniffer class that can be used for the above purpose.
Categories : PHP, PHP Classes, Browsers
Three Cool Classes and One Trick
Categories : PHP, PHP Classes, Graphics, Email
XTemplate, a template class for PHP
Categories : PHP Classes, HTML and PHP, PHP
Request Method Class - seful for situations like form processing or API development. Requires PHP5 for the magic __call() method.
Categories : PHP, PHP Classes, HTTP, Headers
A damaged image generator (class) for validating text. CAPTCHA - Completely Automated Public Turing test to tell Computers and Humans Apart
Categories : PHP, PHP Classes, Security, GD image library, Security
base64 with encryption - encode and decode sessions
Categories : PHP, PHP Classes, Encryption, Sessions
A Timing Class
Categories : PHP, PHP Classes, Date Time
Alternating list with TemplateTamer
Categories : PHP, Templates
Mssql database Manager
Categories : PHP, Databases, MS SQL Server, Classes and Objects, PHP Classes