/app/cache.class.php

https://bitbucket.org/AliGH/ghsaffron · PHP · 85 lines · 58 code · 15 blank · 12 comment · 11 complexity · aeec747c606dd7731a5eda1035c9d87f MD5 · raw file

  1. <?php
  2. /* ===================================
  3. * Author: Nazarkin Roman
  4. * -----------------------------------
  5. * Contacts:
  6. * email - roman@nazarkin.su
  7. * icq - 642971062
  8. * skype - roman444ik
  9. * -----------------------------------
  10. * GitHub:
  11. * https://github.com/NazarkinRoman
  12. * ===================================
  13. */
  14. class MicroCache {
  15. public $patch = 'cachetmp/';
  16. public $lifetime = 3600; // default value - 1 hour
  17. public $c_type = 'memcache';
  18. public $cache_on = true;
  19. public $is_cached = false;
  20. public $memcache_compressed = false;
  21. public $file, $key;
  22. private $memcache;
  23. function __construct($key=false) {
  24. class_exists('Memcache') or $this->c_type = 'file';
  25. if($this->c_type != 'file'){
  26. $this->memcache = new Memcache;
  27. @$this->memcache->connect('localhost', 11211) or $this->c_type = 'file';
  28. }
  29. $this->key = md5( $key===false ? $_SERVER["REQUEST_URI"] : $key);
  30. $this->file = $this->patch . $this->key . '.cache';
  31. }
  32. public function check() {
  33. return $this->is_cached = !$this->cache_on ? false
  34. : $this->c_type == 'file' ?
  35. ( is_readable($this->file) and is_writable($this->file) and (time()-filemtime($this->file) < $this->lifetime) )
  36. : $this->is_cached = ( $this->cache_on and $this->memcache->get($this->key) );
  37. }
  38. public function out() {
  39. return !$this->is_cached ? ''
  40. : $this->c_type == 'file' ?
  41. file_get_contents($this->file)
  42. : $this->memcache->get($this->key);
  43. }
  44. public function start() {
  45. ob_start();
  46. }
  47. public function end() {
  48. $buffer = ob_get_contents();
  49. ob_end_clean();
  50. $this->cache_on and $this->write($buffer);
  51. die ($buffer);
  52. }
  53. public function write($buffer = ''){
  54. if($this->c_type == 'file') {
  55. $fp = @fopen($this->file, 'w') or die("Cannot create cache file : {$this->file}");
  56. if ( @flock($fp, LOCK_EX)) {
  57. fwrite($fp, $buffer);
  58. fflush($fp);
  59. flock($fp, LOCK_UN);
  60. fclose($fp);
  61. }
  62. } else $this->memcache->set($this->key, $buffer, $this->memcache_compressed, $this->lifetime);
  63. }
  64. public function clear($key=false){
  65. $key = $key === false ? $this->key : md5($key);
  66. $file = $this->patch . $this->key . '.cache';
  67. if ($this->c_type == 'file') @unlink($file);
  68. else $this->memcache->delete($key);
  69. }
  70. }