Tuesday, August 4, 2009

A quick guide to Smarty caching

When you first jump into Smarty Template Engine caching it can be a bit confusing and overwhelming till you get your feet wet and begin to understand some core concepts of how Smarty works.  Now that I'm beginning to understand it, I see how we can't live without it!

Basic Caching

Smarty has a _compiled folder which is used to cache the parsed versions of templates (ie - Smarty's "template code" is replaced with actual PHP and stored in the _compiled folder).  Smarty also has a _cache folder which will actually store individual templates.

For smaller web sites, Smarty's basic caching is very effective and simple.  You simply enable caching and define a lifetime

caching = 2; // lifetime is per cache

// set the cache_lifetime for index.tpl to 5 minutes
$smarty->cache_lifetime = 300;
$smarty->display('index.tpl');

// set the cache_lifetime for home.tpl to 1 hour
$smarty->cache_lifetime = 3600;
$smarty->display('home.tpl');

// NOTE: the following $cache_lifetime setting will not work when $caching = 2.
// The cache lifetime for home.tpl has already been set
// to 1 hour, and will no longer respect the value of $cache_lifetime.
// The home.tpl cache will still expire after 1 hour.
$smarty->cache_lifetime = 30; // 30 seconds
$smarty->display('home.tpl');
?>

Group Caching

Smarty offers the ability to group your templates.  So if you need to lets say, clear the templates for the news section of your web site, you can simply execute $smarty->clear_cache(null,'news'); and all of your news template's caches will be cleared.  This same technique can be utilized for caching dynamic pages with a ?id= within the URL.  You can apply multiple group tags to identify a group, or an individual element. In the below example, index.tpl will be used to view all articles, but to decrease database load you want to cache each article's contents. By defining news|$article_id you are creating a sub group of news for each article id, meaning they won't be overwritten by other articles.

caching = 1;

$my_cache_id = $_GET['article_id'];

if(!$smarty->is_cached('index.tpl', 'news|'.$my_cache_id)) {
    // No cache available, do variable assignments here.
    $contents = get_database_contents();
    $smarty->assign($contents);
}

$smarty->display('index.tpl', 'news|'.$my_cache_id);
?>

By utilizing the is_cached() function we see the core benefit of Smarty. If the cache exists, we don't need to run queries to or any parsing on the article itself, so we can skip all of this. This is very beneficial to reduce SQL server load. It's much less server processing to see if a file exists than it is to run queries/parsing on an article.

That's the basics of Smarty caching.

No comments:

Post a Comment