Caching PHP applications using Smarty
Using Smarty is daunting at first, there’s so much it can do. Here’s a way to take advantage of Smarty’s caching functionality in your pre-existing applications.
What we’re going to do is use the PHP4 output buffering and cache the output of your script through that.
Create a simple template on your webserver somewhere. It doesn’t even have to reside in the visible path of the server. In fact, it probably shouldn’t! In that file will be one Smarty variable, $text. This variables is going to hold the entire contents of your script output.
Your script is going to have various inputs that define what gets shown, ie. username, message number, etc. We’re going to cache the output based on those bit of information. In our example that’ll be the uid, $uid of the user.
$smarty = new Smarty;
$smarty->caching = true;
$template = “/home/www/include/templates/text.tpl”;
if($smarty->is_cached( $template, $uid )==false)
// Create new content, cached data is stale or isn’t cached.
$text = “Hello World”;
// Call legacy code that prints directly to the browser
// Get data from database, do other expensive things.
$text .= ob_get_contents();
$smarty->assign(‘text’, $text );
$smarty->display( $template, $uid );
If your legacy code has to interogate the database then you’re saving a huge amount of time doing this. Even if it’s nothing but print statements, chances are Smarty will do it quicker if it’s cached.