我已经将文档(位于此处)中的一些代码混合在一起,以获得更完整的 smarty 缓存示例。另外,我不确定您在示例中使用的是什么,但您应该使用 smarty 的方法来操作缓存。
require('Smarty.class.php');
$smarty = new Smarty;
// 1 Means use the cache time defined in this file,
// 2 means use cache time defined in the cache itself
$smarty->caching = 2;
// set the cache_lifetime for index.tpl to 5 minutes
$smarty->cache_lifetime = 300;
// Check if a cache exists for this file, if one doesn't exist assign variables etc
if(!$smarty->is_cached('index.tpl')) {
$contents = get_database_contents();
$smarty->assign($contents);
}
// Display the output of index.tpl, will be from cache if one exists
$smarty->display('index.tpl');
// set the cache_lifetime for home.tpl to 1 hour
$smarty->cache_lifetime = 3600;
// Check if a cache exists for this file, if one doesn't exist assign variables etc
if(!$smarty->is_cached('home.tpl')) {
$contents = get_database_contents();
$smarty->assign($contents);
}
// Display the output of index.tpl, will be from cache if one exists
$smarty->display('home.tpl');
至于 APC 缓存,它的工作方式与 smarty 相同。它们都将数据存储在文件中一段特定的时间。每次您希望访问数据时,它都会检查缓存是否有效,如果有效则返回缓存值。
但是,如果不使用 smarty,您可以像这样使用 APC:
此示例将数据库查询的结果存储在缓存中,同样,您可以修改它以存储整个页面输出,这样您就不必运行昂贵的PHP 函数频繁。
// A class to make APC management easier
class CacheManager
{
public function get($key)
{
return apc_fetch($key);
}
public function store($key, $data, $ttl)
{
return apc_store($key, $data, $ttl);
}
public function delete($key)
{
return apc_delete($key);
}
}
结合一些逻辑,
function getNews()
{
$query_string = 'SELECT * FROM news ORDER BY date_created DESC limit 5';
// see if this is cached first...
if($data = CacheManager::get(md5($query_string)))
{
// It was stored, return the value
$result = $data;
}
else
{
// It wasn't stored, so run the query
$result = mysql_query($query_string, $link);
$resultsArray = array();
while($line = mysql_fetch_object($result))
{
$resultsArray[] = $line;
}
// Save the result inside the cache for 3600 seconds
CacheManager::set(md5($query_string), $resultsArray, 3600);
}
// Continue on with more functions if necessary
}
此示例在此处稍作修改。