ApcCache.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <?php
  2. namespace Luracast\Restler;
  3. use Luracast\Restler\iCache;
  4. /**
  5. * Class ApcCache provides an APC based cache for Restler
  6. *
  7. * @category Framework
  8. * @package Restler
  9. * @author Joel R. Simpson <joel.simpson@gmail.com>
  10. * @copyright 2013 Luracast
  11. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  12. * @link http://luracast.com/products/restler/
  13. *
  14. */
  15. class ApcCache implements iCache
  16. {
  17. /**
  18. * The namespace that all of the cached entries will be stored under. This allows multiple APIs to run concurrently.
  19. *
  20. * @var string
  21. */
  22. static public $namespace = 'restler';
  23. /**
  24. * store data in the cache
  25. *
  26. *
  27. * @param string $name
  28. * @param mixed $data
  29. *
  30. * @return boolean true if successful
  31. */
  32. public function set($name, $data)
  33. {
  34. function_exists('apc_store') || $this->apcNotAvailable();
  35. try {
  36. return apc_store(self::$namespace . "-" . $name, $data);
  37. } catch
  38. (\Exception $exception) {
  39. return false;
  40. }
  41. }
  42. private function apcNotAvailable()
  43. {
  44. throw new \Exception('APC is not available for use as Restler Cache. Please make sure the module is installed. http://php.net/manual/en/apc.installation.php');
  45. }
  46. /**
  47. * retrieve data from the cache
  48. *
  49. *
  50. * @param string $name
  51. * @param bool $ignoreErrors
  52. *
  53. * @throws \Exception
  54. * @return mixed
  55. */
  56. public function get($name, $ignoreErrors = false)
  57. {
  58. function_exists('apc_fetch') || $this->apcNotAvailable();
  59. try {
  60. return apc_fetch(self::$namespace . "-" . $name);
  61. } catch (\Exception $exception) {
  62. if (!$ignoreErrors) {
  63. throw $exception;
  64. }
  65. return null;
  66. }
  67. }
  68. /**
  69. * delete data from the cache
  70. *
  71. *
  72. * @param string $name
  73. * @param bool $ignoreErrors
  74. *
  75. * @throws \Exception
  76. * @return boolean true if successful
  77. */
  78. public function clear($name, $ignoreErrors = false)
  79. {
  80. function_exists('apc_delete') || $this->apcNotAvailable();
  81. try {
  82. apc_delete(self::$namespace . "-" . $name);
  83. } catch (\Exception $exception) {
  84. if (!$ignoreErrors) {
  85. throw $exception;
  86. }
  87. }
  88. }
  89. /**
  90. * check if the given name is cached
  91. *
  92. *
  93. * @param string $name
  94. *
  95. * @return boolean true if cached
  96. */
  97. public function isCached($name)
  98. {
  99. function_exists('apc_exists') || $this->apcNotAvailable();
  100. return apc_exists(self::$namespace . "-" . $name);
  101. }
  102. }