2009-07-08 4 views
4

난 내 PHP 코드 스마티를 사용하고 있는데 나는 웹 사이트 페이지의 일부는 그래서 난 다음 코드를 사용하는 캐시 좋아 :PHP에서 파일을 캐시하는 가장 좋은 방법은 무엇입니까?

// TOP of script 
ob_start(); // start the output buffer 
$cachefile ="cache/cachefile.html"; 
// normal PHP script 
$smarty->display('somefile.tpl.html') ; 
$fp = fopen($cachefile, 'w'); // open the cache file for writing 
fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file 
fclose($fp); // close the file 
ob_end_flush(); // Send the output to the browser 

을하지만 난 PHP 파일의 끝에서() ob_get_contents를 인쇄 할 때 비어입니다! 실제로 생성 된 캐시 파일 또한 비어 있습니다! 그래서 내가 어떻게 smarty를 사용하여 내가 멋진 캐시를 사용할 수 있지만 내가 어떤 이유로 작동하지 않는 PHP에서 파일을 캐시 할 수 있습니다.

또한 APC 캐시에 대한 정보를 제공해주십시오. 사용 방법? 그것은 내 경우에 사용 가치가있다, 나는 그것이 단지 데이터베이스 쿼리를 캐싱에 대한 얇은, 나는 그것에 대해 PHP 매뉴얼을 읽을 수 있지만 아무것도 얻을 수 없다 :) 탱크.

답변

1

스마트 캐시의보다 완벽한 예를 보려면 설명서의 코드 (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 약간 변경된다.

+0

@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

+0

@mehdi 사용자 정의 캐시 ID를 사용해야하는 것처럼 들리므로 원하는만큼 많은 버전의'index.tpl'를 캐시 할 수 있습니다. 예 : 'news.php'에서'$ smarty-> display ('index.tpl', 'news |'. $ article_id);'도움말 페이지의 경우 'help'라는 캐시 ID를 사용할 수 있습니다. . $ topic' 등 (파이프 문자를 사용하여 캐시 ID를 구성하면 캐시를 선택적으로 지울 수 있습니다 (예 : 모든 뉴스 기사를 한 번에 지 웁니다). – searlea

1

ob_end_flush()를 호출 한 후 ob_get_contents()를 다시 호출한다는 의미입니까? 그렇다면 파일에 쓴 내용은 PHP 메모리에서 "삭제"됩니다.

HTML을 계속 출력하려면 먼저 ob_end_flush를 변수에 저장 한 다음 fwrite로 전달하십시오. 나중에 변수를 사용할 수 있습니다.