You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

119 lines
2.7 KiB

15 years ago
13 years ago
15 years ago
15 years ago
  1. <?php
  2. /**
  3. * A fully-static class that deals with caching.
  4. */
  5. class Cache
  6. {
  7. private static $instance;
  8. private $db;
  9. private $log = true;
  10. private $login;
  11. private $ttl; // TODO
  12. // Yes, another singleton...
  13. private function __construct()
  14. {
  15. // Saving the user's login.
  16. $user = new User();
  17. $this->login = $user->getLogin();
  18. }
  19. function __destruct()
  20. {
  21. }
  22. public static function create()
  23. {
  24. if(!is_object(self::$instance)) {
  25. self::$instance = new Cache();
  26. }
  27. return self::$instance;
  28. }
  29. // Helper function to access cache.
  30. public static function c()
  31. {
  32. $cache = Cache::create();
  33. return call_user_func_array(array($cache, 'handle'), func_get_args());
  34. }
  35. /**
  36. * Fetches or commits an object to cache with the provided key.
  37. *
  38. * Prototype: handle(string $key, ...)
  39. *
  40. * The following fetches an object from cache.
  41. * handle('key')
  42. *
  43. * This commits an object to cache.
  44. * handle('key', $object);
  45. *
  46. * Several objects can be commited to cache in this manner:
  47. * handle('key', $object1, $object2, $object3);
  48. * And retrieved as follows:
  49. * list($object1, $object2, $object3) = handle('key');
  50. */
  51. public function handle($key)
  52. {
  53. $arglist = func_get_args();
  54. $key = $arglist[0];
  55. if(func_num_args() == 1) {
  56. $content = $this->read_cache($key);
  57. if(isset($content) && $content != "") {
  58. return $content;
  59. } else {
  60. return false; // FALSE is better for testing.
  61. }
  62. }
  63. if(func_num_args() == 2) {
  64. return $this->write_cache($key, $arglist[1]);
  65. }
  66. else {
  67. // Cutting a piece of the args.
  68. $content = array_slice($argslist, 1);
  69. return $this->write_cache($key, $content);
  70. }
  71. }
  72. /**
  73. * Serializes data in a proper fashion.
  74. */
  75. private function write_cache($key, $object)
  76. {
  77. $data = str_replace("'", "\\'", base64_encode(gzcompress(serialize($object))));
  78. $time = date(DATE_ISO8601, time());
  79. $cd = new \modl\CacheDAO();
  80. $c = new \modl\Cache();
  81. $c->session = $this->login;
  82. $c->data = $data;
  83. $c->name = $key;
  84. $c->timestamp = $time;
  85. $cd->set($c);
  86. }
  87. /**
  88. * Unserializes data.
  89. */
  90. private function read_cache($key)
  91. {
  92. $cd = new \modl\CacheDAO();
  93. $var = $cd->get($this->login, $key);
  94. if(isset($var)) {
  95. return unserialize(gzuncompress(base64_decode(str_replace("\\'", "'", $var->data))));
  96. } else {
  97. return false;
  98. }
  99. }
  100. }
  101. ?>