Caching is a way of improving a Web page's performance by saving the executed version of a page as a static file. This allows the server to handle multiple requests for the same page with only one execution of the underlying PHP script. Caching can be applied to any type of content provided to the browser by the server but it makes particular sense to use it with templated pages. Smarty caching refers to a built-in caching that's easy to use.
Enabling Caching in Smarty
To turn on caching for a page, set the "caching" attribute to 1:
require('Smarty.class.php');
$page = new Smarty();
$page->caching = 1;
$page->display('demotpl.tpl');
The first time this code is run, the resulting HTML page will be sent to the Web browser and saved as a file in Smarty's cache directory. Subsequent executions of this page will result in the cached version being sent to the Web browser.
Adjusting the Cache Expiration or Lifetime
Every cached page has an associated timestamp, indicating for how long the cached page is good. By default this is one hour from the time the file was created. This is important to pay attention to because given the above code, the cached version of the page will be provided to the requesting user, no matter what changes might have been made to the template or the data used in the template in the interim. For example, if you were to use caching like this on a message board, users would effectively only see updates every hour, as in-between requests would receive the saved version of the page.
To adjust the smarty cache lifetime of a page, set the "caching" attribute to 2 and set the "cache_lifetime" attribute to some number in seconds:
require('Smarty.class.php');
$page = new Smarty();
$page->caching = 2;
$page->cache_lifetime = 1800; // 30 minutes
$page->display('template.tpl');
Checking the Cache
Smarty only takes advantage of a cached version of a page once it gets to the display() (or fetch()) method call. But if a PHP page has some amount of activity, like retrieving from a database or file the information to be used on the page, that PHP code will still be executed. This makes the cache less efficient than it could be. To improve upon this system, check for a valid cached version of the page prior to doing any potentially unnecessary execution:
require('Smarty.class.php');
$page = new Smarty();
$page->caching = 1;
if (!$page->is_cached('template.tpl')) { // If the page isn't cached...
// Do whatever is necessary.
$page->assign('placeholder', 'value');
// Etc.
}
$page->display('template.tpl');
|