Simple PHP file cache

I try to share my experience on write php code, in this time i will share simple php librarary for caching content, this very simple. If you interesting you can get it from my dropbox.

This the code:
 
class Cache
{
 private $cachedir  = '';
 private $expire    = 60;
 
 public function __construct($cachedir = ''){
  if ($cachedir !== ''){
   if (!is_dir($cachedir) or !is_writable($cachedir)){
    throw new Exception('Cache directory must be a valid writeable directory.'); 
   }
   $this->cachedir = $cachedir;
  }
 }
 
 public function set($id, $data){
  $file = $this->cachedir . $id;
  if ( file_exists( $file ) ){
   unlink($file);
  }
  if (!file_put_contents($file, serialize($data))){
   throw new Exception('Error writing data to cache file.');
  }
 }
 
 public function get($id){
  $file = glob($this->cachedir . $id);
        $file = array_shift($file);
  if (!$data = file_get_contents($file))
  {
   throw new Exception('Error reading data from cache file.');
  }
  return unserialize($data);
 }

 public function valid($id,$set=''){
        if($set !== ''){
            return (bool)$set;
        }
  $file = glob($this->cachedir . $id);
        $file = array_shift($file);
  return (bool)(time() - filemtime($file) <= $this->expire);
 }
    
    public function delete($id){
        $path = $this->cachedir . $id ;
        if( file_exists( $path ) ) {
            unlink( $path );
        }
    }
}
Example usage :
<!DOCTYPE HTML>
<head>
 <meta http-equiv="content-type" content="text/html" />
 <meta name="author" content="Jaksu" />
 <title>Simple File Caching</title>
</head>

<body>
<?php
    include 'cache.php';
    $cache      = new Cache('cache/');
    $cache_data = 'simple file caching example';
    $cache_id   = '123';
    if( $cache->valid( $cache_id ) ) {
        $data   = $cache->get( $cache_id );
    } else {
        $data   = $cache_data;
        $cache->set( $cache_id , $cache_data );
    }
    
    echo $data;
?>


</body>
</html>

0 komentar:

Posting Komentar