class PhpBackend

Same name in other branches
  1. 9 core/lib/Drupal/Core/Cache/PhpBackend.php \Drupal\Core\Cache\PhpBackend
  2. 10 core/lib/Drupal/Core/Cache/PhpBackend.php \Drupal\Core\Cache\PhpBackend
  3. 11.x core/lib/Drupal/Core/Cache/PhpBackend.php \Drupal\Core\Cache\PhpBackend

Defines a PHP cache implementation.

Stores cache items in a PHP file using a storage that implements Drupal\Component\PhpStorage\PhpStorageInterface.

This is fast because of PHP's opcode caching mechanism. Once a file's content is stored in PHP's opcode cache, including it doesn't require reading the contents from a filesystem. Instead, PHP will use the already compiled opcodes stored in memory.

Hierarchy

Expanded class hierarchy of PhpBackend

Related topics

2 files declare their use of PhpBackend
ChainedFastBackendTest.php in core/tests/Drupal/KernelTests/Core/Cache/ChainedFastBackendTest.php
PhpBackendTest.php in core/tests/Drupal/KernelTests/Core/Cache/PhpBackendTest.php

File

core/lib/Drupal/Core/Cache/PhpBackend.php, line 22

Namespace

Drupal\Core\Cache
View source
class PhpBackend implements CacheBackendInterface {
    
    /**
     * @var string
     */
    protected $bin;
    
    /**
     * Array to store cache objects.
     */
    protected $cache = [];
    
    /**
     * The cache tags checksum provider.
     *
     * @var \Drupal\Core\Cache\CacheTagsChecksumInterface
     */
    protected $checksumProvider;
    
    /**
     * Constructs a PhpBackend object.
     *
     * @param string $bin
     *   The cache bin for which the object is created.
     * @param \Drupal\Core\Cache\CacheTagsChecksumInterface $checksum_provider
     *   The cache tags checksum provider.
     */
    public function __construct($bin, CacheTagsChecksumInterface $checksum_provider) {
        $this->bin = 'cache_' . $bin;
        $this->checksumProvider = $checksum_provider;
    }
    
    /**
     * {@inheritdoc}
     */
    public function get($cid, $allow_invalid = FALSE) {
        return $this->getByHash($this->normalizeCid($cid), $allow_invalid);
    }
    
    /**
     * Fetch a cache item using a hashed cache ID.
     *
     * @param string $cidhash
     *   The hashed version of the original cache ID after being normalized.
     * @param bool $allow_invalid
     *   (optional) If TRUE, a cache item may be returned even if it is expired or
     *   has been invalidated.
     *
     * @return bool|mixed
     */
    protected function getByHash($cidhash, $allow_invalid = FALSE) {
        if ($file = $this->storage()
            ->getFullPath($cidhash)) {
            $cache = @(include $file);
        }
        if (isset($cache)) {
            return $this->prepareItem($cache, $allow_invalid);
        }
        return FALSE;
    }
    
    /**
     * {@inheritdoc}
     */
    public function setMultiple(array $items) {
        foreach ($items as $cid => $item) {
            $this->set($cid, $item['data'], isset($item['expire']) ? $item['expire'] : CacheBackendInterface::CACHE_PERMANENT, isset($item['tags']) ? $item['tags'] : []);
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function getMultiple(&$cids, $allow_invalid = FALSE) {
        $ret = [];
        foreach ($cids as $cid) {
            if ($item = $this->get($cid, $allow_invalid)) {
                $ret[$item->cid] = $item;
            }
        }
        $cids = array_diff($cids, array_keys($ret));
        return $ret;
    }
    
    /**
     * Prepares a cached item.
     *
     * Checks that items are either permanent or did not expire, and returns data
     * as appropriate.
     *
     * @param object $cache
     *   An item loaded from self::get() or self::getMultiple().
     * @param bool $allow_invalid
     *   If FALSE, the method returns FALSE if the cache item is not valid.
     *
     * @return mixed
     *   The item with data as appropriate or FALSE if there is no
     *   valid item to load.
     */
    protected function prepareItem($cache, $allow_invalid) {
        if (!isset($cache->data)) {
            return FALSE;
        }
        // Check expire time.
        $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= REQUEST_TIME;
        // Check if invalidateTags() has been called with any of the item's tags.
        if (!$this->checksumProvider
            ->isValid($cache->checksum, $cache->tags)) {
            $cache->valid = FALSE;
        }
        if (!$allow_invalid && !$cache->valid) {
            return FALSE;
        }
        return $cache;
    }
    
    /**
     * {@inheritdoc}
     */
    public function set($cid, $data, $expire = Cache::PERMANENT, array $tags = []) {
        assert(Inspector::assertAllStrings($tags), 'Cache Tags must be strings.');
        $item = (object) [
            'cid' => $cid,
            'data' => $data,
            'created' => round(microtime(TRUE), 3),
            'expire' => $expire,
            'tags' => array_unique($tags),
            'checksum' => $this->checksumProvider
                ->getCurrentChecksum($tags),
        ];
        $this->writeItem($this->normalizeCid($cid), $item);
    }
    
    /**
     * {@inheritdoc}
     */
    public function delete($cid) {
        $this->storage()
            ->delete($this->normalizeCid($cid));
    }
    
    /**
     * {@inheritdoc}
     */
    public function deleteMultiple(array $cids) {
        foreach ($cids as $cid) {
            $this->delete($cid);
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function deleteAll() {
        $this->storage()
            ->deleteAll();
    }
    
    /**
     * {@inheritdoc}
     */
    public function invalidate($cid) {
        $this->invalidatebyHash($this->normalizeCid($cid));
    }
    
    /**
     * Invalidate one cache item.
     *
     * @param string $cidhash
     *   The hashed version of the original cache ID after being normalized.
     */
    protected function invalidatebyHash($cidhash) {
        if ($item = $this->getByHash($cidhash)) {
            $item->expire = REQUEST_TIME - 1;
            $this->writeItem($cidhash, $item);
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function invalidateMultiple(array $cids) {
        foreach ($cids as $cid) {
            $this->invalidate($cid);
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function invalidateAll() {
        foreach ($this->storage()
            ->listAll() as $cidhash) {
            $this->invalidatebyHash($cidhash);
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function garbageCollection() {
    }
    
    /**
     * {@inheritdoc}
     */
    public function removeBin() {
        $this->cache = [];
        $this->storage()
            ->deleteAll();
    }
    
    /**
     * Writes a cache item to PhpStorage.
     *
     * @param string $cidhash
     *   The hashed version of the original cache ID after being normalized.
     * @param object $item
     *   The cache item to store.
     */
    protected function writeItem($cidhash, \stdClass $item) {
        $content = '<?php return unserialize(' . var_export(serialize($item), TRUE) . ');';
        $this->storage()
            ->save($cidhash, $content);
    }
    
    /**
     * Gets the PHP code storage object to use.
     *
     * @return \Drupal\Component\PhpStorage\PhpStorageInterface
     */
    protected function storage() {
        if (!isset($this->storage)) {
            $this->storage = PhpStorageFactory::get($this->bin);
        }
        return $this->storage;
    }
    
    /**
     * Ensures a normalized cache ID.
     *
     * @param string $cid
     *   The passed in cache ID.
     *
     * @return string
     *   A normalized cache ID.
     */
    protected function normalizeCid($cid) {
        return Crypt::hashBase64($cid);
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title
CacheBackendInterface::CACHE_PERMANENT constant Indicates that the item should never be removed unless explicitly deleted.
PhpBackend::$bin protected property
PhpBackend::$cache protected property Array to store cache objects.
PhpBackend::$checksumProvider protected property The cache tags checksum provider.
PhpBackend::delete public function Deletes an item from the cache. Overrides CacheBackendInterface::delete
PhpBackend::deleteAll public function Deletes all cache items in a bin. Overrides CacheBackendInterface::deleteAll
PhpBackend::deleteMultiple public function Deletes multiple items from the cache. Overrides CacheBackendInterface::deleteMultiple
PhpBackend::garbageCollection public function Performs garbage collection on a cache bin. Overrides CacheBackendInterface::garbageCollection
PhpBackend::get public function Returns data from the persistent cache. Overrides CacheBackendInterface::get
PhpBackend::getByHash protected function Fetch a cache item using a hashed cache ID.
PhpBackend::getMultiple public function Returns data from the persistent cache when given an array of cache IDs. Overrides CacheBackendInterface::getMultiple
PhpBackend::invalidate public function Marks a cache item as invalid. Overrides CacheBackendInterface::invalidate
PhpBackend::invalidateAll public function Marks all cache items as invalid. Overrides CacheBackendInterface::invalidateAll
PhpBackend::invalidatebyHash protected function Invalidate one cache item.
PhpBackend::invalidateMultiple public function Marks cache items as invalid. Overrides CacheBackendInterface::invalidateMultiple
PhpBackend::normalizeCid protected function Ensures a normalized cache ID.
PhpBackend::prepareItem protected function Prepares a cached item.
PhpBackend::removeBin public function Remove a cache bin. Overrides CacheBackendInterface::removeBin
PhpBackend::set public function Stores data in the persistent cache. Overrides CacheBackendInterface::set
PhpBackend::setMultiple public function Store multiple items in the persistent cache. Overrides CacheBackendInterface::setMultiple
PhpBackend::storage protected function Gets the PHP code storage object to use.
PhpBackend::writeItem protected function Writes a cache item to PhpStorage.
PhpBackend::__construct public function Constructs a PhpBackend object.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.