스마트 캐시의보다 완벽한 예를 보려면 설명서의 코드 (here)를 정리했습니다. 또한, 귀하의 예제에서 무엇을 사용하고 있는지 잘 모르겠지만, 캐시를 조작하기 위해 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와 동일한 방식으로 작동합니다. 둘 다 특정 시간 동안 파일에 데이터를 저장합니다. 데이터에 액세스하려고 할 때마다 캐시가 유효한지 확인하고 캐시가 유효하면 캐시 값을 반환합니다.
이 예는 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-> display ('index.tpl') 만 가지고 있기 때문에; news.tpl 같은 나머지 페이지는 내 index.tpl 센터에 들어와 있습니다. {include file = $ page_center} 다음은 news.php 파일에 있습니다. $ smarty-> assign ('page_center', 'news.tpl '); 하지만 캐싱을 사용하도록 설정하면 news.tpl이 아닌 페이지 센터의 기본 콘텐츠가 표시되지만 캐시가 잘 작동하면 정상적으로 작동합니다. – mehdi
@mehdi 사용자 정의 캐시 ID를 사용해야하는 것처럼 들리므로 원하는만큼 많은 버전의'index.tpl'를 캐시 할 수 있습니다. 예 : 'news.php'에서'$ smarty-> display ('index.tpl', 'news |'. $ article_id);'도움말 페이지의 경우 'help'라는 캐시 ID를 사용할 수 있습니다. . $ topic' 등 (파이프 문자를 사용하여 캐시 ID를 구성하면 캐시를 선택적으로 지울 수 있습니다 (예 : 모든 뉴스 기사를 한 번에 지 웁니다). – searlea