スマートキャッシュのより完全な例については、ドキュメントのコードの一部(here)をマッシュアップしました。また、私はあなたの例で何を使用していたのか分かりませんが、スマートのメソッドを使ってキャッシュを操作する必要があります。
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と同じように動作します。彼らは両方とも特定の時間の間、ファイルにデータを格納します。データにアクセスするたびに、キャッシュが有効かどうかをチェックし、有効な場合はキャッシュの値を返します。
この例では、DBクエリの結果をキャッシュに保存する場合と同様に、ページ出力全体を格納する代わりに変更することができます高価な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
}
この例はわずかにhereから変更されています。
@lan Elliottはい、Smartyキャッシングは良いアイデアですが、使用できません。私は$ smarty-> display( 'index.tpl')しか持っていないので、 news.tplのような他のページは私のindex.tplセンターに入っています。{include file = $ page_center}次にnews.phpファイルにあります。$ smarty-> assign( 'page_center'、 'news.tpl ');しかし、キャッシュを有効にすると、まだnews.tplではなくページセンターのデフォルトのコンテンツが表示されますが、キャッシングがうまく動作しているとうまくいきます。 – mehdi
@mehdiそれはあなたが望むように 'index.tpl'の多くのバージョンをキャッシュできるカスタムキャッシュIDを使う必要があるようです。例えば'news.php'では' $ smarty-> display( 'index.tpl'、 'news |'。$ article_id); 'ヘルプページでは' help 'というキャッシュIDを使うことができます。 $ topic'など(パイプ文字を使用してキャッシュIDを構造化することで、キャッシュを選択的にクリアすることができます。 – searlea