UseCacheBackendTrait.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Drupal\Core\Cache;
  3. /**
  4. * Provides methods to use a cache backend while respecting a 'use caches' flag.
  5. */
  6. trait UseCacheBackendTrait {
  7. /**
  8. * Cache backend instance.
  9. *
  10. * @var \Drupal\Core\Cache\CacheBackendInterface
  11. */
  12. protected $cacheBackend;
  13. /**
  14. * Flag whether caches should be used or skipped.
  15. *
  16. * @var bool
  17. */
  18. protected $useCaches = TRUE;
  19. /**
  20. * Fetches from the cache backend, respecting the use caches flag.
  21. *
  22. * @param string $cid
  23. * The cache ID of the data to retrieve.
  24. *
  25. * @return object|false
  26. * The cache item or FALSE on failure.
  27. *
  28. * @see \Drupal\Core\Cache\CacheBackendInterface::get()
  29. */
  30. protected function cacheGet($cid) {
  31. if ($this->useCaches && $this->cacheBackend) {
  32. return $this->cacheBackend->get($cid);
  33. }
  34. return FALSE;
  35. }
  36. /**
  37. * Stores data in the persistent cache, respecting the use caches flag.
  38. *
  39. * @param string $cid
  40. * The cache ID of the data to store.
  41. * @param mixed $data
  42. * The data to store in the cache.
  43. * Some storage engines only allow objects up to a maximum of 1MB in size to
  44. * be stored by default. When caching large arrays or similar, take care to
  45. * ensure $data does not exceed this size.
  46. * @param int $expire
  47. * One of the following values:
  48. * - CacheBackendInterface::CACHE_PERMANENT: Indicates that the item should
  49. * not be removed unless it is deleted explicitly.
  50. * - A Unix timestamp: Indicates that the item will be considered invalid
  51. * after this time, i.e. it will not be returned by get() unless
  52. * $allow_invalid has been set to TRUE. When the item has expired, it may
  53. * be permanently deleted by the garbage collector at any time.
  54. * @param array $tags
  55. * An array of tags to be stored with the cache item. These should normally
  56. * identify objects used to build the cache item, which should trigger
  57. * cache invalidation when updated. For example if a cached item represents
  58. * a node, both the node ID and the author's user ID might be passed in as
  59. * tags. For example array('node' => array(123), 'user' => array(92)).
  60. *
  61. * @see \Drupal\Core\Cache\CacheBackendInterface::set()
  62. */
  63. protected function cacheSet($cid, $data, $expire = Cache::PERMANENT, array $tags = []) {
  64. if ($this->cacheBackend && $this->useCaches) {
  65. $this->cacheBackend->set($cid, $data, $expire, $tags);
  66. }
  67. }
  68. }