WithLocalCache.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\Memcache;
  7. use OCP\Cache\CappedMemoryCache;
  8. use OCP\ICache;
  9. /**
  10. * Wrap a cache instance with an extra later of local, in-memory caching
  11. */
  12. class WithLocalCache implements ICache {
  13. private ICache $inner;
  14. private CappedMemoryCache $cached;
  15. public function __construct(ICache $inner, int $localCapacity = 512) {
  16. $this->inner = $inner;
  17. $this->cached = new CappedMemoryCache($localCapacity);
  18. }
  19. public function get($key) {
  20. if (isset($this->cached[$key])) {
  21. return $this->cached[$key];
  22. } else {
  23. $value = $this->inner->get($key);
  24. if (!is_null($value)) {
  25. $this->cached[$key] = $value;
  26. }
  27. return $value;
  28. }
  29. }
  30. public function set($key, $value, $ttl = 0) {
  31. $this->cached[$key] = $value;
  32. return $this->inner->set($key, $value, $ttl);
  33. }
  34. public function hasKey($key) {
  35. return isset($this->cached[$key]) || $this->inner->hasKey($key);
  36. }
  37. public function remove($key) {
  38. unset($this->cached[$key]);
  39. return $this->inner->remove($key);
  40. }
  41. public function clear($prefix = '') {
  42. $this->cached->clear();
  43. return $this->inner->clear($prefix);
  44. }
  45. public static function isAvailable(): bool {
  46. return false;
  47. }
  48. }