1
<?php
2
/*
3
  Belokan Micro Framework
4
  Licensed under GNU GPL
5
  http://gitorious.org/belokan
6
  ---
7
  Belokan/Cache.php:
8
  Cache system
9
*/
10
11
class Belokan_Cache {
12
  
13
  private
14
    $_file,
15
    $_updateType,
16
    $_updateValue,
17
    $_buffer;
18
    
19
  public function __construct ($key=null, $cond_type='time', $cond_value='3600')
20
  {
21
    $config = Belokan_Config::getInstance();
22
    
23
    if ($key == null) $key = md5($_SERVER['REQUEST_URI']);
24
    
25
    if ($config->exists('dir', 'cache'))
26
      $this->_file = $config->get('dir', 'cache').$key.'.cache';
27
    else if ($config->get('log', 'belokan')) {
28
      Belokan_Log::getInstance()->add('Belokan', 'ERROR: No cache directory specified in the configuration.');
29
      exit;
30
    }
31
    
32
    $this->_updateType = $cond_type;
33
    $this->_updateValue = $cond_value;
34
    
35
    $this->_buffer = null;
36
  }
37
  
38
  public function get ()
39
  {
40
    if (!file_exists($this->_file)) return false;
41
    if ($this->_updateType == 'forced') return false;
42
    if ($this->_updateType == 'time' && (time() - filemtime($this->_file)) > $this->_updateValue)
43
      return false;
44
    if ($this->_updateType == 'date' && date($this->_updateValue, filemtime($this->_file)) != date($this->_updateValue))
45
      return false;
46
    
47
    readfile($this->_file);
48
    return true;
49
  }
50
  
51
  public function start ()
52
  {
53
    ob_start();
54
  }
55
  
56
  public function end ()
57
  {
58
    $this->_buffer = ob_get_clean();
59
    $this->save();
60
    echo $this->_buffer;
61
  }
62
  
63
  private function save ()
64
  {
65
    if ($cacheFile = fopen($this->_file, 'w')) {
66
      fwrite($cacheFile, $this->_buffer);
67
      fclose($cacheFile);
68
    }
69
  }
70
  
71
}