You are here

class MongoDBCache in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 vendor/doctrine/cache/lib/Doctrine/Common/Cache/MongoDBCache.php \Doctrine\Common\Cache\MongoDBCache

MongoDB cache provider.

@since 1.1 @author Jeremy Mikola <jmikola@gmail.com>

Hierarchy

Expanded class hierarchy of MongoDBCache

1 file declares its use of MongoDBCache
MongoDBCacheTest.php in vendor/doctrine/cache/tests/Doctrine/Tests/Common/Cache/MongoDBCacheTest.php

File

vendor/doctrine/cache/lib/Doctrine/Common/Cache/MongoDBCache.php, line 32

Namespace

Doctrine\Common\Cache
View source
class MongoDBCache extends CacheProvider {

  /**
   * The data field will store the serialized PHP value.
   */
  const DATA_FIELD = 'd';

  /**
   * The expiration field will store a MongoDate value indicating when the
   * cache entry should expire.
   *
   * With MongoDB 2.2+, entries can be automatically deleted by MongoDB by
   * indexing this field wit the "expireAfterSeconds" option equal to zero.
   * This will direct MongoDB to regularly query for and delete any entries
   * whose date is older than the current time. Entries without a date value
   * in this field will be ignored.
   *
   * The cache provider will also check dates on its own, in case expired
   * entries are fetched before MongoDB's TTLMonitor pass can expire them.
   *
   * @see http://docs.mongodb.org/manual/tutorial/expire-data/
   */
  const EXPIRATION_FIELD = 'e';

  /**
   * @var MongoCollection
   */
  private $collection;

  /**
   * Constructor.
   *
   * This provider will default to the write concern and read preference
   * options set on the MongoCollection instance (or inherited from MongoDB or
   * MongoClient). Using an unacknowledged write concern (< 1) may make the
   * return values of delete() and save() unreliable. Reading from secondaries
   * may make contain() and fetch() unreliable.
   *
   * @see http://www.php.net/manual/en/mongo.readpreferences.php
   * @see http://www.php.net/manual/en/mongo.writeconcerns.php
   * @param MongoCollection $collection
   */
  public function __construct(MongoCollection $collection) {
    $this->collection = $collection;
  }

  /**
   * {@inheritdoc}
   */
  protected function doFetch($id) {
    $document = $this->collection
      ->findOne(array(
      '_id' => $id,
    ), array(
      self::DATA_FIELD,
      self::EXPIRATION_FIELD,
    ));
    if ($document === null) {
      return false;
    }
    if ($this
      ->isExpired($document)) {
      $this
        ->doDelete($id);
      return false;
    }
    return unserialize($document[self::DATA_FIELD]->bin);
  }

  /**
   * {@inheritdoc}
   */
  protected function doContains($id) {
    $document = $this->collection
      ->findOne(array(
      '_id' => $id,
    ), array(
      self::EXPIRATION_FIELD,
    ));
    if ($document === null) {
      return false;
    }
    if ($this
      ->isExpired($document)) {
      $this
        ->doDelete($id);
      return false;
    }
    return true;
  }

  /**
   * {@inheritdoc}
   */
  protected function doSave($id, $data, $lifeTime = 0) {
    $result = $this->collection
      ->update(array(
      '_id' => $id,
    ), array(
      '$set' => array(
        self::EXPIRATION_FIELD => $lifeTime > 0 ? new MongoDate(time() + $lifeTime) : null,
        self::DATA_FIELD => new MongoBinData(serialize($data), MongoBinData::BYTE_ARRAY),
      ),
    ), array(
      'upsert' => true,
      'multiple' => false,
    ));
    return isset($result['ok']) ? $result['ok'] == 1 : true;
  }

  /**
   * {@inheritdoc}
   */
  protected function doDelete($id) {
    $result = $this->collection
      ->remove(array(
      '_id' => $id,
    ));
    return isset($result['n']) ? $result['n'] == 1 : true;
  }

  /**
   * {@inheritdoc}
   */
  protected function doFlush() {

    // Use remove() in lieu of drop() to maintain any collection indexes
    $result = $this->collection
      ->remove();
    return isset($result['ok']) ? $result['ok'] == 1 : true;
  }

  /**
   * {@inheritdoc}
   */
  protected function doGetStats() {
    $serverStatus = $this->collection->db
      ->command(array(
      'serverStatus' => 1,
      'locks' => 0,
      'metrics' => 0,
      'recordStats' => 0,
      'repl' => 0,
    ));
    $collStats = $this->collection->db
      ->command(array(
      'collStats' => 1,
    ));
    return array(
      Cache::STATS_HITS => null,
      Cache::STATS_MISSES => null,
      Cache::STATS_UPTIME => isset($serverStatus['uptime']) ? (int) $serverStatus['uptime'] : null,
      Cache::STATS_MEMORY_USAGE => isset($collStats['size']) ? (int) $collStats['size'] : null,
      Cache::STATS_MEMORY_AVAILABLE => null,
    );
  }

  /**
   * Check if the document is expired.
   *
   * @param array $document
   * @return boolean
   */
  private function isExpired(array $document) {
    return isset($document[self::EXPIRATION_FIELD]) && $document[self::EXPIRATION_FIELD] instanceof MongoDate && $document[self::EXPIRATION_FIELD]->sec < time();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
Cache::STATS_HITS constant
Cache::STATS_MEMORY_AVAILABLE constant
Cache::STATS_MEMORY_AVAILIABLE constant Only for backward compatibility (may be removed in next major release)
Cache::STATS_MEMORY_USAGE constant
Cache::STATS_MISSES constant
Cache::STATS_UPTIME constant
CacheProvider::$namespace private property The namespace to prefix all cache ids with.
CacheProvider::$namespaceVersion private property The namespace version.
CacheProvider::contains public function Tests if an entry exists in the cache. Overrides Cache::contains
CacheProvider::delete public function Deletes a cache entry. Overrides Cache::delete
CacheProvider::deleteAll public function Deletes all cache entries in the current cache namespace. Overrides ClearableCache::deleteAll
CacheProvider::DOCTRINE_NAMESPACE_CACHEKEY constant
CacheProvider::doFetchMultiple protected function Default implementation of doFetchMultiple. Each driver that supports multi-get should owerwrite it. 4
CacheProvider::fetch public function Fetches an entry from the cache. Overrides Cache::fetch
CacheProvider::fetchMultiple public function Returns an associative array of values for keys is found in cache. Overrides MultiGetCache::fetchMultiple
CacheProvider::flushAll public function Flushes all cache entries, globally. Overrides FlushableCache::flushAll
CacheProvider::getNamespace public function Retrieves the namespace that prefixes all cache ids.
CacheProvider::getNamespaceCacheKey private function Returns the namespace cache key.
CacheProvider::getNamespacedId private function Prefixes the passed id with the configured namespace value.
CacheProvider::getNamespaceVersion private function Returns the namespace version.
CacheProvider::getStats public function Retrieves cached information from the data store. Overrides Cache::getStats
CacheProvider::save public function Puts data into the cache. Overrides Cache::save
CacheProvider::setNamespace public function Sets the namespace to prefix all cache ids with. 1
MongoDBCache::$collection private property
MongoDBCache::DATA_FIELD constant The data field will store the serialized PHP value.
MongoDBCache::doContains protected function Tests if an entry exists in the cache. Overrides CacheProvider::doContains
MongoDBCache::doDelete protected function Deletes a cache entry. Overrides CacheProvider::doDelete
MongoDBCache::doFetch protected function Fetches an entry from the cache. Overrides CacheProvider::doFetch
MongoDBCache::doFlush protected function Flushes all cache entries. Overrides CacheProvider::doFlush
MongoDBCache::doGetStats protected function Retrieves cached information from the data store. Overrides CacheProvider::doGetStats
MongoDBCache::doSave protected function Puts data into the cache. Overrides CacheProvider::doSave
MongoDBCache::EXPIRATION_FIELD constant The expiration field will store a MongoDate value indicating when the cache entry should expire.
MongoDBCache::isExpired private function Check if the document is expired.
MongoDBCache::__construct public function Constructor.