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