ClosureCacheAdapter.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace Guzzle\Cache;
  3. /**
  4. * Cache adapter that defers to closures for implementation
  5. */
  6. class ClosureCacheAdapter implements CacheAdapterInterface
  7. {
  8. /**
  9. * @var array Mapping of method names to callables
  10. */
  11. protected $callables;
  12. /**
  13. * The callables array is an array mapping the actions of the cache adapter to callables.
  14. * - contains: Callable that accepts an $id and $options argument
  15. * - delete: Callable that accepts an $id and $options argument
  16. * - fetch: Callable that accepts an $id and $options argument
  17. * - save: Callable that accepts an $id, $data, $lifeTime, and $options argument
  18. *
  19. * @param array $callables array of action names to callable
  20. *
  21. * @throws \InvalidArgumentException if the callable is not callable
  22. */
  23. public function __construct(array $callables)
  24. {
  25. // Validate each key to ensure it exists and is callable
  26. foreach (array('contains', 'delete', 'fetch', 'save') as $key) {
  27. if (!array_key_exists($key, $callables) || !is_callable($callables[$key])) {
  28. throw new \InvalidArgumentException("callables must contain a callable {$key} key");
  29. }
  30. }
  31. $this->callables = $callables;
  32. }
  33. public function contains($id, array $options = null)
  34. {
  35. return call_user_func($this->callables['contains'], $id, $options);
  36. }
  37. public function delete($id, array $options = null)
  38. {
  39. return call_user_func($this->callables['delete'], $id, $options);
  40. }
  41. public function fetch($id, array $options = null)
  42. {
  43. return call_user_func($this->callables['fetch'], $id, $options);
  44. }
  45. public function save($id, $data, $lifeTime = false, array $options = null)
  46. {
  47. return call_user_func($this->callables['save'], $id, $data, $lifeTime, $options);
  48. }
  49. }