2012-05-26 6 views
0

PHP를 캐싱하는 것에 대한 정보를 찾고 있습니다. 내가 발견 한 모든 정보는 특정 시간 간격 (매시간)에 PHP 파일을 캐시하는 것입니다. 50 페이지 뷰마다 캐시 할 수있는 방법이 있습니까? 50 페이지 뷰마다 캐시 된 파일이 만료됩니다.PHP 캐시는 페이지 조회 수에 따라 만료됩니다.

누구든지 이에 대해 알 수 있습니까?

미리 감사드립니다.

+0

우리가있어 타사 캐싱을 도움이되기를 바랍니다. 어느 쪽을 사용합니까? – Leri

+0

안녕 PLB, 난 여전히 정보를 찾고 있어요, 내가 찾은 참조 링크는 http://www.theukwebdesigncompany.com/articles/php-caching.php이지만, 때로는 모든 페이지 뷰가 아닌 모든 캐싱에 대해 이야기합니다. 제 3 자 캐싱은 무엇에 대해 언급하고 있습니까? –

답변

1

Heres 해결책은 데이터베이스를 사용하는 파일 기반 캐시 대신 PDO sqlite (이 방법은 캐시 파일 데이터베이스를 삭제하여 모든 캐시를 지우는 것)를 사용하는 대신에 함께 사용합니다.

아래쪽을 보면 작동 방식을 볼 수 있습니다. 50 개의 히트 수를 기록한 후 행을 삭제하고 리디렉션하므로 새 복사본을 생성 할 수 있습니다. 이 PHP에서

sqlite.cache.class.php

<?php 
/** 
* PDO sqlite cache class 
* You can include('sqlite.cache.class.php'); this class 
*/ 
class sqlite_cache{ 
    private $db; 

    function __construct($dsn){ 
     $this->dsn = $dsn; 
     $this->chkSetup(); 
    } 

    /*Singleton Connect*/ 
    private function connect(){ 
     if (!$this->db instanceof PDO){ 
      $this->db = new PDO($this->dsn); 
      $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     } 
    } 

    /*Raw Select*/ 
    public function rawSelect($sql){ 
     $this->connect(); 
     return $this->db->query($sql)->fetchAll(PDO::FETCH_ASSOC); 
    } 

    public function get($fieldname=null, $id=null){ 
     $this->connect(); 
     $sql = "SELECT * FROM cache WHERE $fieldname = :id"; 
     $statement = $this->db->prepare($sql); 
     $statement->bindParam(':id', $id, PDO::PARAM_STR); 
     $statement->execute(); 
     return $statement->fetchAll(PDO::FETCH_ASSOC); 
    } 

    /*Insert*/ 
    public function put($values){ 
     $this->connect(); 
     $fieldnames = array_keys($values[0]); 
     $sql = "INSERT INTO cache "; 
     $fields = '('.implode(' ,', $fieldnames).')'; 
     $bound = '(:'.implode(', :', $fieldnames).')'; 
     $sql .= $fields.' VALUES '.$bound; 

     $statement = $this->db->prepare($sql); 
     foreach($values as $vals){ 
      $statement->execute($vals); 
     } 
    } 

    /*Update*/ 
    public function update($fieldname, $value, $pk, $id){ 
     $this->connect(); 
     $sql = "UPDATE cache SET $fieldname = :value WHERE $pk = :id"; 
     $statement = $this->db->prepare($sql); 
     $statement->bindParam(':id', $id, PDO::PARAM_STR); 
     $statement->bindParam(':value', $value, PDO::PARAM_STR); 
     $statement->execute(); 
    } 

    /*Update Hits*/ 
    public function add_hit($id){ 
     $this->connect(); 
     $sql = "UPDATE cache SET hits = hits + 1 WHERE url = :id"; 
     $statement = $this->db->prepare($sql); 
     $statement->bindParam(':id', $id, PDO::PARAM_STR); 
     $statement->execute(); 
    } 

    /*Delete*/ 
    public function delete($id){ 
     $this->connect(); 
     $sql = "DELETE FROM cache WHERE url = :id"; 
     $statement = $this->db->prepare($sql); 
     $statement->bindParam(':id', $id, PDO::PARAM_STR); 
     $statement->execute(); 
    } 


    /*Database Setup*/ 
    private function chkSetup(){ 
     $dso = explode(':',$this->dsn); 

     if(file_exists($dso[1])){ 
      return; 
     }else{ 
      $this->connect(); 
      //Create Table 
      $sql ="CREATE TABLE cache (id INTEGER PRIMARY KEY, 
              title TEXT, 
              url TEXT, 
              hits INTEGER, 
              date INTEGER, 
              contents TEXT)"; 
      $this->db->query($sql); 
      header("refresh:0;url=./"); 
      die; 
     } 
    } 
} 
?> 

index.php를

<?php 
include('sqlite.cache.class.php'); 
$cache = new sqlite_cache('sqlite:./cache.db'); 

//Check if cache exists 
$cache_result = $cache->get('url',$_SERVER['REQUEST_URI']); 
//Exists 
if(!empty($cache_result)){ 
    //Add Hit 
    $cache->add_hit($_SERVER['REQUEST_URI']); 

    //Delete If over 50 hits 
    if($cache_result[0]['hits']>=50){ 
     $cache->delete($_SERVER['REQUEST_URI']); 
     header('Location: '.$_SERVER['REQUEST_URI']); 
     die; 
    } 

    echo $cache_result[0]['contents']; 
}else{ 
    //Generate your page contents ect 
    ob_start(); 

    /////////////////////////////// 
    //Your script code goes here 
    /////////////////////////////// 

    echo 'Your content'; 

    //End your script code///////// 
    /////////////////////////////// 
    $return = ob_get_contents(); 
    ob_end_clean(); 

    //Before output build values to put in cache 
    $cache_contents = array(array('id'=>NULL, 
            'title'=>'Page Title', 
            'url'=>$_SERVER['REQUEST_URI'], 
            'hits'=>'0', 
            'date'=>time(), 
            'contents'=>$return)); 

    //Store cache 
    $cache->put($cache_contents); 
    echo $return; 
} 

?> 
+0

안녕하세요 로렌스. 귀하의 방법은 almpost 완벽하다는 점을 제외하고 페이지보기의 특정 숫자 이후, 내가 새 페이지를 새로 고칠 때 빈 페이지를 표시하고, 한 번 더 새로 고침하여 새 내용을 업데이트 할 수 있습니다. 그래서,이 큰 PHP 파일에 어떤 작은 버그가 있습니까? –

+0

'$ cache-> put ($ cache_contents); 뒤에 편집에서'echo $ return;'(마지막 줄)을 추가했습니다. '포함 시켰습니까? PHP 파일을 올바르게 사용하는 방법을 모르겠습니다.() 그것을 포함시킬 수있는만큼 크지 않습니다. –

+0

아, PHP 파일을 올바르게 사용하는 방법을 모르겠습니다. 실제로, 나는 단지 PHP 파일 mysite.com/test.php에 전체 코드를 복사하여 붙여 넣은 다음 원하는 페이지로 http://google.com을 편집하므로 mysite.com/test.php를 my 브라우저는 원하는 페이지의 내용을 보여줍니다. 이것은 PHP 코드를 사용하는 잘못된 방법입니까? –

0

정말 낮은 기술로이 문제에 대한 해결책을 얻을 수 있습니다.

URL에 도달 할 때마다 임시 파일을 카운터로 만들 수 있습니다. 이 같은 것을 사용 -에서 차용

// recursively remove a directory 
function rrmdir($dir) { 
    foreach(glob($dir . '/*') as $file) { 
     if ($file != "." && $file != "..") { 
      if(is_dir($file)) 
      rrmdir($file); 
      else 
      unlink($file); 
     } 
    } 
    rmdir($dir); 
} 



$fileCount = count(glob($tempfile_directory."/*")); 
if ($fileCount >= $someLimit){ 
    rrmdir($tempfile_directory); // clear the counter 
    mkdir($tempfile_directory); 
    // clear the cached server data and refresh. 
} 
touch($tempfile_directory . '/' . time()); // create a new dummy counter file 

재귀 삭제 기능 -

$tempfile_directory에있는 파일의 개수가 크거나 $someLimit 같다 http://www.php.net/manual/en/function.rmdir.php#108113이 폴더가 비워 및 캐시 된 데이터 새로 고침됩니다.

+0

그래서 실제로 $ someLimit 변수는 페이지로드 횟수가 아닙니다. 캐시 된 페이지 수만입니다. –

+0

아니요 ... '$ someLimit'은 캐시 데이터를 새로 고침하기 전에 허용 할 페이지 뷰 수입니다. – Lix

+0

감사합니다. Lix! 나는 지금 그것을 얻었다 –

관련 문제