CacheCollector.php 8.17 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
<?php

/**
 * @file
 * Contains \Drupal\Core\Cache\CacheCollector.
 */

namespace Drupal\Core\Cache;

use Drupal\Core\DestructableInterface;
use Drupal\Core\Lock\LockBackendInterface;

/**
 * Default implementation for CacheCollectorInterface.
 *
 * By default, the class accounts for caches where calling functions might
 * request keys that won't exist even after a cache rebuild. This prevents
 * situations where a cache rebuild would be triggered over and over due to a
 * 'missing' item. These cases are stored internally as a value of NULL. This
 * means that the CacheCollector::get() method must be overridden if caching
 * data where the values can legitimately be NULL, and where
 * CacheCollector->has() needs to correctly return (equivalent to
 * array_key_exists() vs. isset()). This should not be necessary in the majority
 * of cases.
 */
abstract class CacheCollector implements CacheCollectorInterface, DestructableInterface {

  /**
   * The cache id that is used for the cache entry.
   *
   * @var string
   */
  protected $cid;

  /**
   * A list of tags that are used for the cache entry.
   *
   * @var array
   */
  protected $tags;

  /**
   * The cache backend that should be used.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cache;

  /**
   * The lock backend that should be used.
   *
   * @var \Drupal\Core\Lock\LockBackendInterface
   */
  protected $lock;

  /**
   * An array of keys to add to the cache on service termination.
   *
   * @var array
   */
  protected $keysToPersist = array();

  /**
   * An array of keys to remove from the cache on service termination.
   *
   * @var array
   */
  protected $keysToRemove = array();

  /**
   * Storage for the data itself.
   *
   * @var array
   */
  protected $storage = array();

  /**
   * Stores the cache creation time.
   *
   * This is used to check if an invalidated cache item has been overwritten in
   * the meantime.
   *
   * @var int
   */
  protected $cacheCreated;

  /**
   * Flag that indicates of the cache has been invalidated.
   *
   * @var bool
   */
  protected $cacheInvalidated = FALSE;

  /**
   * Indicates if the collected cache was already loaded.
   *
   * The collected cache is lazy loaded when an entry is set, get or deleted.
   *
   * @var bool
   */
  protected $cacheLoaded = FALSE;

  /**
   * Constructs a CacheCollector object.
   *
   * @param string $cid
   *   The cid for the array being cached.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   The cache backend.
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
   *   The lock backend.
   * @param array $tags
   *   (optional) The tags to specify for the cache item.
   */
  public function __construct($cid, CacheBackendInterface $cache, LockBackendInterface $lock, $tags = array()) {
    $this->cid = $cid;
    $this->cache = $cache;
    $this->tags = $tags;
    $this->lock = $lock;
  }

  /**
   * {@inheritdoc}
   */
  public function has($key) {
    // Make sure the value is loaded.
    $this->get($key);
    return isset($this->storage[$key]) || array_key_exists($key, $this->storage);
  }

  /**
   * {@inheritdoc}
   */
  public function get($key) {
    $this->lazyLoadCache();
    if (isset($this->storage[$key]) || array_key_exists($key, $this->storage)) {
      return $this->storage[$key];
    }
    else {
      return $this->resolveCacheMiss($key);
    }
  }

  /**
   * Implements \Drupal\Core\Cache\CacheCollectorInterface::set().
   *
   * This is not persisted by default. In practice this means that setting a
   * value will only apply while the object is in scope and will not be written
   * back to the persistent cache. This follows a similar pattern to static vs.
   * persistent caching in procedural code. Extending classes may wish to alter
   * this behavior, for example by adding a call to persist().
   */
  public function set($key, $value) {
    $this->lazyLoadCache();
    $this->storage[$key] = $value;
    // The key might have been marked for deletion.
    unset($this->keysToRemove[$key]);
    $this->invalidateCache();

  }

  /**
   * {@inheritdoc}
   */
  public function delete($key) {
    $this->lazyLoadCache();
    unset($this->storage[$key]);
    $this->keysToRemove[$key] = $key;
    // The key might have been marked for persisting.
    unset($this->keysToPersist[$key]);
    $this->invalidateCache();
  }

  /**
   * Flags an offset value to be written to the persistent cache.
   *
   * @param string $key
178
   *   The key that was requested.
179 180 181
   * @param bool $persist
   *   (optional) Whether the offset should be persisted or not, defaults to
   *   TRUE. When called with $persist = FALSE the offset will be unflagged so
182
   *   that it will not be written at the end of the request.
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
   */
  protected function persist($key, $persist = TRUE) {
    $this->keysToPersist[$key] = $persist;
  }

  /**
   * Resolves a cache miss.
   *
   * When an offset is not found in the object, this is treated as a cache
   * miss. This method allows classes using this implementatio to look up the
   * actual value and allow it to be cached.
   *
   * @param sring $key
   *   The offset that was requested.
   *
   * @return mixed
   *   The value of the offset, or NULL if no value was found.
   */
  abstract protected function resolveCacheMiss($key);

  /**
   * Writes a value to the persistent cache immediately.
   *
   * @param bool $lock
   *   (optional) Whether to acquire a lock before writing to cache. Defaults to
   *   TRUE.
   */
  protected function updateCache($lock = TRUE) {
    $data = array();
    foreach ($this->keysToPersist as $offset => $persist) {
      if ($persist) {
        $data[$offset] = $this->storage[$offset];
      }
    }
    if (empty($data) && empty($this->keysToRemove)) {
      return;
    }

    // Lock cache writes to help avoid stampedes.
    $lock_name = $this->cid . ':' . __CLASS__;
    if (!$lock || $this->lock->acquire($lock_name)) {
      // Set and delete operations invalidate the cache item. Try to also load
      // an eventually invalidated cache entry, only update an invalidated cache
      // entry if the creation date did not change as this could result in an
      // inconsistent cache.
      if ($cache = $this->cache->get($this->cid, $this->cacheInvalidated)) {
        if ($this->cacheInvalidated && $cache->created != $this->cacheCreated) {
          // We have invalidated the cache in this request and got a different
          // cache entry. Do not attempt to overwrite data that might have been
          // changed in a different request. We'll let the cache rebuild in
          // later requests.
          $this->cache->delete($this->cid);
          $this->lock->release($lock_name);
          return;
        }
        $data = array_merge($cache->data, $data);
      }
      // Remove keys marked for deletion.
      foreach ($this->keysToRemove as $delete_key) {
        unset($data[$delete_key]);
      }
244
      $this->cache->set($this->cid, $data, Cache::PERMANENT, $this->tags);
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
      if ($lock) {
        $this->lock->release($lock_name);
      }
    }

    $this->keysToPersist = array();
    $this->keysToRemove = array();
  }

  /**
   * {@inheritdoc}
   */
  public function reset() {
    $this->storage = array();
    $this->keysToPersist = array();
    $this->keysToRemove = array();
    $this->cacheLoaded = FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function clear() {
    $this->reset();
    if ($this->tags) {
270
      Cache::deleteTags($this->tags);
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    }
    else {
      $this->cache->delete($this->cid);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function destruct() {
    $this->updateCache();
  }

  /**
   * Loads the cache if not already done.
   */
  protected function lazyLoadCache() {
    if ($this->cacheLoaded) {
      return;
    }
    // The cache was not yet loaded, set flag to TRUE.
    $this->cacheLoaded = TRUE;

    if ($cache = $this->cache->get($this->cid)) {
      $this->cacheCreated = $cache->created;
      $this->storage = $cache->data;
    }
  }

  /**
   * Invalidate the cache.
   */
  protected function invalidateCache() {
    // Invalidate the cache to make sure that other requests immediately see the
    // deletion before this request is terminated.
    $this->cache->invalidate($this->cid);
    $this->cacheInvalidated = TRUE;
  }

}