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.
—–/home/www/include/templates/text.tpl—–
{$text}
—–/home/www/include/templates/text.tpl—–—–/home/www/htdocs/test.php—–
require(‘Smarty.class.php’);
$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”;
ob_start();
// Call legacy code that prints directly to the browser
// Get data from database, do other expensive things.
$text .= ob_get_contents();
ob_end_clean();
$smarty->assign(‘text’, $text );
}$smarty->display( $template, $uid );
—–/home/www/htdocs/test.php—–
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.