You are here

public function CacheBackendMongodb::set in MongoDB 8

Implements Drupal\Core\Cache\CacheBackendInterface::set().

Stores data in the persistent cache.

Parameters

string $cid: The cache ID of the data to store.

mixed $data: The data to store in the cache. Some storage engines only allow objects up to a maximum of 1MB in size to be stored by default. When caching large arrays or similar, take care to ensure $data does not exceed this size.

int $expire: One of the following values:

  • CacheBackendInterface::CACHE_PERMANENT: Indicates that the item should not be removed unless it is deleted explicitly.
  • A Unix timestamp: Indicates that the item will be considered invalid after this time, i.e. it will not be returned by get() unless $allow_invalid has been set to TRUE. When the item has expired, it may be permanently deleted by the garbage collector at any time.

array $tags: An array of tags to be stored with the cache item. These should normally identify objects used to build the cache item, which should trigger cache invalidation when updated. For example if a cached item represents a node, both the node ID and the author's user ID might be passed in as tags. For example array('node' => array(123), 'user' => array(92)).

Overrides CacheBackendInterface::set

File

src/CacheBackendMongodb.php, line 178
Definition of Drupal\mongodb/CacheBackendMongodb.

Class

CacheBackendMongodb
Defines MongoDB cache implementation.

Namespace

Drupal\mongodb

Code

public function set($cid, $data, $expire = CacheBackendInterface::CACHE_PERMANENT, array $tags = array()) {

  // We do not serialize configurations as we're sure we always get
  // them as arrays. This will be much faster as mongo knows how to
  // store arrays directly.
  $serialized = !is_scalar($data) && $this->collection
    ->getName() != 'cache_config';
  $entry = array(
    '_id' => (string) $cid,
    'cid' => (string) $cid,
    'serialized' => $serialized,
    'created' => round(microtime(TRUE), 3),
    'expire' => $expire == CacheBackendInterface::CACHE_PERMANENT ? CacheBackendInterface::CACHE_PERMANENT : new \MongoDate($expire),
    'data' => $serialized ? serialize($data) : $data,
    'tags' => implode(' ', $tags),
    'checksum' => $this->checksumProvider
      ->getCurrentChecksum($tags),
  );

  // Use MongoBinData for non-UTF8 strings.
  if (is_string($entry['data']) && !drupal_validate_utf8($entry['data'])) {
    $entry['data'] = new \MongoBinData($entry['data']);
  }
  try {
    $this->collection
      ->save($entry, array(
      'w' => 0,
    ));
  } catch (\Exception $e) {

    // The database may not be available, so we'll ignore cache_set requests.
  }
}