Creating Multiple Caches of a Page
Many PHP applications use a system where one template handles all the data of a certain type. For example, blogging software has a template for viewing posts or an image gallery has a template for showing an image. The specific content to be shown on that page--the actual blog post or gallery image--is normally controlled by a value passed in the URL. In such cases caching the main template is of no value, as somepage.php?id=1 and somepage.php?id=2 should be showing entirely different content.
The solution is to tell Smarty about the mitigating factors for a template. Then Smarty can cache each variation on that template:
require('Smarty.class.php');
$page = new Smarty();
$page->caching = 1;
// Check for a valid ID...
// Type-cast the received ID:
$page_id = (int) $_GET['id'];
$page->display('template.tpl', $page_id);
The is_cached() function can also check the validity of a cached version of such a page:
require('Smarty.class.php');
$page = new Smarty();
$page->caching = 1;
// Check for a valid ID...
// Type-cast the received ID:
$page_id = (int) $_GET['id'];
if (!$page->is_cached('template.tpl', $page_id)) { // If the page isn't cached...
// Do whatever is necessary.
}
$page->display('template.tpl', $page_id);
Creating Non-Cached Elements
Many templated sites have elements that should not be cached, like advertising banners. To tell Smarty not to cache a section of a template, use the {insert} function.
{insert name="some_thing" var1='some value' var2='other value'}
This has the effect of calling a function named insert_some_thing, which must be defined in your PHP code. The values are passed as an associative array. So the above line is the equivalent of
insert_some_thing(array('var1' = 'some value', 'var2' = 'other value'));
The function should return the results of its operation.
How to Smarty Clear Cache
The cache of a specific page can be cleared using the clear_cache() method:
require('Smarty.class.php');
$page = new Smarty();
$page->clear_cache('somepage.tpl');
Every cached page can be cleared using clear_all_cache():
require('Smarty.class.php');
$page = new Smarty();
$page->clear_all_cache();
Either of these functions might be used for debugging purposes, or as part of some greater programming logic.
|