cacheresource.memcache.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Memcache CacheResource
  4. *
  5. * CacheResource Implementation based on the KeyValueStore API to use
  6. * memcache as the storage resource for Smarty's output caching.
  7. *
  8. * Note that memcache has a limitation of 256 characters per cache-key.
  9. * To avoid complications all cache-keys are translated to a sha1 hash.
  10. *
  11. * @package CacheResource-examples
  12. * @author Rodney Rehm
  13. */
  14. class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore {
  15. /**
  16. * memcache instance
  17. * @var Memcache
  18. */
  19. protected $memcache = null;
  20. public function __construct()
  21. {
  22. $this->memcache = new Memcache();
  23. $this->memcache->addServer( '127.0.0.1', 11211 );
  24. }
  25. /**
  26. * Read values for a set of keys from cache
  27. *
  28. * @param array $keys list of keys to fetch
  29. * @return array list of values with the given keys used as indexes
  30. * @return boolean true on success, false on failure
  31. */
  32. protected function read(array $keys)
  33. {
  34. $_keys = $lookup = array();
  35. foreach ($keys as $k) {
  36. $_k = sha1($k);
  37. $_keys[] = $_k;
  38. $lookup[$_k] = $k;
  39. }
  40. $_res = array();
  41. $res = $this->memcache->get($_keys);
  42. foreach ($res as $k => $v) {
  43. $_res[$lookup[$k]] = $v;
  44. }
  45. return $_res;
  46. }
  47. /**
  48. * Save values for a set of keys to cache
  49. *
  50. * @param array $keys list of values to save
  51. * @param int $expire expiration time
  52. * @return boolean true on success, false on failure
  53. */
  54. protected function write(array $keys, $expire=null)
  55. {
  56. foreach ($keys as $k => $v) {
  57. $k = sha1($k);
  58. $this->memcache->set($k, $v, 0, $expire);
  59. }
  60. return true;
  61. }
  62. /**
  63. * Remove values from cache
  64. *
  65. * @param array $keys list of keys to delete
  66. * @return boolean true on success, false on failure
  67. */
  68. protected function delete(array $keys)
  69. {
  70. foreach ($keys as $k) {
  71. $k = sha1($k);
  72. $this->memcache->delete($k);
  73. }
  74. return true;
  75. }
  76. /**
  77. * Remove *all* values from cache
  78. *
  79. * @return boolean true on success, false on failure
  80. */
  81. protected function purge()
  82. {
  83. return $this->memcache->flush();
  84. }
  85. }