I've just finished adding caching to my template class which I first posted details of in "PHP Tip: Extract, Variable Variables and Templating". Here's an example of implementing caching:
<?phprequire('template-engine-v2.inc.php');$oTemplate = new Template('test.php');$oTemplate->AddCacheCondition('home');if (!$oTemplate->IsCached()) {$oTemplate->Set('title', 'Do links on your site make sense out of context?');$oTemplate->Set('author', 'Ed Eliot');$oTemplate->Set('content', new Template('content.php'));}echo $oTemplate->Display();?>
The class now supports two additional methods:
- SetCacheLength($iCacheLength) - this takes a single parameter which specifies the number of seconds you want the output cached for.
- AddCacheCondition($vCondition) - this takes a string or array representing one or more data values which should be used to form the cache key. You might add the current post id, for example, as a condition to ensure individual caching of each post.
When sub-templates are directly assigned to the Set method of a parent template they inherit the parent's cache settings. If you want to specify caching properties for sub-templates individually you'll need to instead assign their output to the parent template.
Download version 2 of the template class. You'll also need to download a copy of my caching class. Alternatively you can view the source of the cache class.
