Cache.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace ActiveRecord;
  3. use Closure;
  4. /**
  5. * Cache::get('the-cache-key', function() {
  6. * # this gets executed when cache is stale
  7. * return "your cacheable datas";
  8. * });
  9. */
  10. class Cache
  11. {
  12. static $adapter = null;
  13. static $options = array();
  14. /**
  15. * Initializes the cache.
  16. *
  17. * With the $options array it's possible to define:
  18. * - expiration of the key, (time in seconds)
  19. * - a namespace for the key
  20. *
  21. * this last one is useful in the case two applications use
  22. * a shared key/store (for instance a shared Memcached db)
  23. *
  24. * Ex:
  25. * $cfg_ar = ActiveRecord\Config::instance();
  26. * $cfg_ar->set_cache('memcache://localhost:11211',array('namespace' => 'my_cool_app',
  27. * 'expire' => 120
  28. * ));
  29. *
  30. * In the example above all the keys expire after 120 seconds, and the
  31. * all get a postfix 'my_cool_app'.
  32. *
  33. * (Note: expiring needs to be implemented in your cache store.)
  34. *
  35. * @param string $url URL to your cache server
  36. * @param array $options Specify additional options
  37. */
  38. public static function initialize($url, $options=array())
  39. {
  40. if ($url)
  41. {
  42. $url = parse_url($url);
  43. $file = ucwords(Inflector::instance()->camelize($url['scheme']));
  44. $class = "ActiveRecord\\$file";
  45. require_once __DIR__ . "/cache/$file.php";
  46. static::$adapter = new $class($url);
  47. }
  48. else
  49. static::$adapter = null;
  50. static::$options = array_merge(array('expire' => 30, 'namespace' => ''),$options);
  51. }
  52. public static function flush()
  53. {
  54. if (static::$adapter)
  55. static::$adapter->flush();
  56. }
  57. public static function get($key, $closure)
  58. {
  59. $key = static::get_namespace() . $key;
  60. if (!static::$adapter)
  61. return $closure();
  62. if (!($value = static::$adapter->read($key)))
  63. static::$adapter->write($key,($value = $closure()),static::$options['expire']);
  64. return $value;
  65. }
  66. private static function get_namespace()
  67. {
  68. return (isset(static::$options['namespace']) && strlen(static::$options['namespace']) > 0) ? (static::$options['namespace'] . "::") : "";
  69. }
  70. }
  71. ?>