Home arrow MySQL arrow Page 3 - Writing Your Own Template Caching Class In PHP
MYSQL

Writing Your Own Template Caching Class In PHP


Writing your own template caching class with PHP doesn't necessarily mean that you have to invent your own template tags, as Havard shows us in this article...

Author Info:
By: Havard Lindset
Rating: 5 stars5 stars5 stars5 stars5 stars / 13
November 19, 2002
TABLE OF CONTENTS:
  1. · Writing Your Own Template Caching Class In PHP
  2. · How Is It Supposed To Work?
  3. · The Code Explained (contd.)
  4. · The Code Explained (contd.)
  5. · Real-World Examples
  6. · Conclusion

print this article
SEARCH DEVARTICLES

Writing Your Own Template Caching Class In PHP - The Code Explained (contd.)
(Page 3 of 6 )

This method is slightly more complicated than the two methods above. Let's take a closer look at the code:

if ($this->_caching == true && $this->isCached($file, $id)) {
$output = $this->_getCache($file, $id);
} else {


This code checks if caching is turned on, and also if there is a cached version available. If there's a cached version available, it fetches it.

$output = $this->_getOutput($file);

if ($this->_caching == true) {
$this->_addCache($output, $file, $id);
}
}


This part of the code gets executed either if caching is turned off, or if the cached version is outdated. The _getOutput() method parses the template and returns it. The "if" construct checks if caching is turned on, and makes a new cache file if it is.

function _getOutput($file)
{
extract($this->_variables);
$file = realpath($file);

if (file_exists($file)) {
ob_start();
include($file);
$output = ob_get_contents();
ob_end_clean();
} else {
trigger_error("Failed opening the template file '$file'. The file doesn't exist.", E_USER_ERROR);
}

return !empty($output) ? $output : false;
}


The _getOutput() method is used for parsing and returning a template. Let's dissect the method.

extract($this->_variables);

The extract function is used for extracting an associative array.

Array
(
[one] => 1
[two] => 2
[three] => 3
)


An array like the one above will make the variables $one, $two and $three based on the associative indexes.

$file = realpath($file);

If you used a relative path when calling the display() or fetch() method, realpath() will convert it to a full path, which makes it usable in the include. If you don't use the realpath() function, the include will fail.

if (file_exists($file)) {
ob_start();
include($file);
$output = ob_get_contents();
ob_end_clean();
} else {
trigger_error("Failed opening the template file '$file'. The file doesn't exist.", E_USER_ERROR);
}


This "if" construct checks if the template file exists, and triggers an error if it doesn't. The capturing of the template works like this: output buffering starts, the file is parsed simply by using the include construct, and then the captured output is put into the $output variable. When all this is done, the buffer is released.

return !empty($output) ? $output : false;

This simply returns $output as long as it isn't empty. If $output is empty, the boolean value false will be returned instead. If you haven't seen this type of comparison operator before, you can read about it on this page in the PHP manual. It's called the ternary operator.

To set the $_cacheDir property, we will use the method setCacheDir():

function setCacheDir($dir)
{
$dir = realpath($dir);

if (is_dir($dir) && is_writable($dir)) {
$this->_cacheDir = $dir;
} else {
trigger_error("The cache directory '$dir' either doesn't exist, or it cannot be written to by PHP", E_USER_WARNING);
$this->_cacheDir = '';
$this->_caching = false;
}
}


Once again, you can see we're using the realpath function to retrieve the full path. The first if construct in this method simply checks if $dir is a directory, and if PHP has access to write in it using the is_dir() and is_writable() functions. If it doesn't exist, or PHP doesn't have write access, caching will therefore be turned off.

We will need a function to set the lifetime of the cached files too. To do this, we use the setCacheLifetime() method.

function setCacheLifetime($seconds)
{
if (is_numeric($seconds)) {
$this->_cacheLifetime = $seconds;
}
}


This method is very straightforward. It simply checks if $seconds is a numerical value, and sets the $_cacheLifetime property accordingly. We need a method to turn caching on and off too. For this, we make the setCaching() method:

function setCaching($state)
{
if (is_bool($state)) {
$this->_caching = $state;
}
}


This function is almost identical to the setCacheLifetime() function. This time we check whether $state is a boolean value. The last few methods have been a breeze. It's time to make some more complicated stuff again. It's time to make the methods for checking, adding and retrieving cached files. We'll start with the isCached() method for checking if a template file is cached:

function isCached($file, $id = false)
{
$id = $id ? md5($id . basename($file)) : md5(basename($file));
$filename = $this->_cacheDir . '/' . $id . '/' . basename($file);

if (is_file($filename)) {
clearstatcache();

if (filemtime($filename) > (time() - $this->_cacheLifetime)) {
$isCached = true;
}
}

return isset($isCached) ? true : false;


I'm going to split up the method in different parts again.

$id = $id ? md5($id . basename($file)) : md5(basename($file));
$filename = $this->_cacheDir . '/' . $id . '/' . basename($file);


This part of the code retrieves the name of the cached file we're going to check. The directory name is generated by making an md5 hash of both the $id and the filename of the template, or just the filename of the template. If $id is set then the hash will consist of both. The basename() function is used for extracting only the filename out of the path in $file.
blog comments powered by Disqus
MYSQL ARTICLES

- MySQL and BLOBs
- Two Lessons in ASP and MySQL
- Lord Of The Strings Part 2
- Lord Of The Strings Part 1
- Importing Data into MySQL with Navicat
- Building a Sustainable Web Site
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- PhpED 3.2 More Features Than You Can Poke ...
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- Security and Sessions in PHP
- Setup Your Personal Reminder System Using PHP
- Create a IP-Country Database Using PERL and ...
- Developing a Dynamic Document Search in PHP ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials