<?php
class cache 
{
  // door Wim Mariën
  // http://www.gdx.be/
  
  
  
  // VARS                                                   /
  // directory with .cache files
  private $dir = './cache/';
  private $filename = NULL;
  
  protected $caching = false;
  
  
  // __construct                                             /  
  // PUBLIC (duh!)
  // cache::__construct()
  // AUTOMATIC
  public function __construct ($dir=NULL)
  {
    if(isset($dir))
      $this->dir = $dir;
      
    if(substr($this->dir, -1) != '/')
      $this->dir .= '/';
  }
  
  
  // __destruct                                             /  
  // PUBLIC (duh!)
  // cache::__destruct()
  // AUTOMATIC
  public function __destruct ()
  {
    $this->dir = NULL;
  }
  
  
  // start                                                  /
  // PUBLIC
  // cache::start([string] filename)
  public function start ($filename)
  {
    
    $this->filename = $filename;
    if(isset($filename) && !is_file($this->dir.$filename.'.cache'))
    {
      ob_start();
      $this->caching = true;
    }
    else
    {
      echo $this->readCache($filename);
      exit();
    }
  }
  
  
  // write                                                  /
  // PUBLIC
  // cache::write ([string] filename)
  public function write ($file='')
  {
    if(empty($file) && !empty($this->filename))
      $file = $this->filename;
    elseif(empty($file) && empty($this->filename))
      return false;
    
    if($this->caching)
    {
      $content = ob_get_contents();
      ob_end_clean();
      $this->updateCache($file, $content);
      return $content;
    }
  }
  
  
  // updateCache                                            /
  // PRIVATE
  // cache::updateCache ([string] filename, [string] content)
  // write a .cache file (by update)
  private function updateCache ($file, $content)
  {
    $cachefile = fopen($this->dir.$file.'.cache', 'w');
    fwrite($cachefile, $content);
    fclose($cachefile);
    return true;
  }
  
  
  // readCache                                              /
  // PUBLIC
  // cache::readCache([string] filename)
  // read a .cache file
  public function readCache($file)
  {
    $cachefile = fopen($this->dir.$file.'.cache', "r");
    
    while(!feof($cachefile))
    {
      $content .= fgets($cachefile, 4096);
    }
    fclose($cachefile);
    
    return $content;
  }

  // deleteCache
  // PUBLIC
  // cache::deleteCache([string] filename)
  // delete a .cache file
  public function deleteCache($file)
  {
    if(unlink($this->dir.$file.'.cache'))
      return true;
    else
      return false;
  }

}
?>