3 namespace Drupal\Core\Cache;
6 * Stores cache items in the Alternative PHP Cache User Cache (APCu).
8 class ApcuBackend implements CacheBackendInterface {
11 * The name of the cache bin to use.
18 * Prefix for all keys in the storage that belong to this site.
22 protected $sitePrefix;
25 * Prefix for all keys in this cache bin.
27 * Includes the site-specific prefix in $sitePrefix.
34 * The cache tags checksum provider.
36 * @var \Drupal\Core\Cache\CacheTagsChecksumInterface
38 protected $checksumProvider;
41 * Constructs a new ApcuBackend instance.
44 * The name of the cache bin.
45 * @param string $site_prefix
46 * The prefix to use for all keys in the storage that belong to this site.
47 * @param \Drupal\Core\Cache\CacheTagsChecksumInterface $checksum_provider
48 * The cache tags checksum provider.
50 public function __construct($bin, $site_prefix, CacheTagsChecksumInterface $checksum_provider) {
52 $this->sitePrefix = $site_prefix;
53 $this->checksumProvider = $checksum_provider;
54 $this->binPrefix = $this->sitePrefix . '::' . $this->bin . '::';
58 * Prepends the APCu user variable prefix for this bin to a cache item ID.
61 * The cache item ID to prefix.
64 * The APCu key for the cache item ID.
66 public function getApcuKey($cid) {
67 return $this->binPrefix . $cid;
73 public function get($cid, $allow_invalid = FALSE) {
74 $cache = apcu_fetch($this->getApcuKey($cid));
75 return $this->prepareItem($cache, $allow_invalid);
81 public function getMultiple(&$cids, $allow_invalid = FALSE) {
82 // Translate the requested cache item IDs to APCu keys.
84 foreach ($cids as $cid) {
85 $map[$this->getApcuKey($cid)] = $cid;
88 $result = apcu_fetch(array_keys($map));
91 foreach ($result as $key => $item) {
92 $item = $this->prepareItem($item, $allow_invalid);
94 $cache[$map[$key]] = $item;
100 $cids = array_diff($cids, array_keys($cache));
105 * Returns all cached items, optionally limited by a cache ID prefix.
107 * APCu is a memory cache, shared across all server processes. To prevent
108 * cache item clashes with other applications/installations, every cache item
109 * is prefixed with a unique string for this site. Therefore, functions like
110 * apcu_clear_cache() cannot be used, and instead, a list of all cache items
111 * belonging to this application need to be retrieved through this method
114 * @param string $prefix
115 * (optional) A cache ID prefix to limit the result to.
117 * @return \APCUIterator
118 * An APCUIterator containing matched items.
120 protected function getAll($prefix = '') {
121 return $this->getIterator('/^' . preg_quote($this->getApcuKey($prefix), '/') . '/');
125 * Prepares a cached item.
127 * Checks that the item is either permanent or did not expire.
129 * @param \stdClass $cache
130 * An item loaded from cache_get() or cache_get_multiple().
131 * @param bool $allow_invalid
132 * If TRUE, a cache item may be returned even if it is expired or has been
133 * invalidated. See ::get().
136 * The cache item or FALSE if the item expired.
138 protected function prepareItem($cache, $allow_invalid) {
139 if (!isset($cache->data)) {
143 $cache->tags = $cache->tags ? explode(' ', $cache->tags) : [];
145 // Check expire time.
146 $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= REQUEST_TIME;
148 // Check if invalidateTags() has been called with any of the entry's tags.
149 if (!$this->checksumProvider->isValid($cache->checksum, $cache->tags)) {
150 $cache->valid = FALSE;
153 if (!$allow_invalid && !$cache->valid) {
163 public function set($cid, $data, $expire = CacheBackendInterface::CACHE_PERMANENT, array $tags = []) {
164 assert('\Drupal\Component\Assertion\Inspector::assertAllStrings($tags)', 'Cache tags must be strings.');
165 $tags = array_unique($tags);
166 $cache = new \stdClass();
168 $cache->created = round(microtime(TRUE), 3);
169 $cache->expire = $expire;
170 $cache->tags = implode(' ', $tags);
171 $cache->checksum = $this->checksumProvider->getCurrentChecksum($tags);
172 // APCu serializes/unserializes any structure itself.
173 $cache->serialized = 0;
174 $cache->data = $data;
176 // Expiration is handled by our own prepareItem(), not APCu.
177 apcu_store($this->getApcuKey($cid), $cache);
183 public function setMultiple(array $items = []) {
184 foreach ($items as $cid => $item) {
185 $this->set($cid, $item['data'], isset($item['expire']) ? $item['expire'] : CacheBackendInterface::CACHE_PERMANENT, isset($item['tags']) ? $item['tags'] : []);
192 public function delete($cid) {
193 apcu_delete($this->getApcuKey($cid));
199 public function deleteMultiple(array $cids) {
200 apcu_delete(array_map([$this, 'getApcuKey'], $cids));
206 public function deleteAll() {
207 apcu_delete($this->getIterator('/^' . preg_quote($this->binPrefix, '/') . '/'));
213 public function garbageCollection() {
214 // APCu performs garbage collection automatically.
220 public function removeBin() {
221 apcu_delete($this->getIterator('/^' . preg_quote($this->binPrefix, '/') . '/'));
227 public function invalidate($cid) {
228 $this->invalidateMultiple([$cid]);
234 public function invalidateMultiple(array $cids) {
235 foreach ($this->getMultiple($cids) as $cache) {
236 $this->set($cache->cid, $cache, REQUEST_TIME - 1);
243 public function invalidateAll() {
244 foreach ($this->getAll() as $data) {
245 $cid = str_replace($this->binPrefix, '', $data['key']);
246 $this->set($cid, $data['value'], REQUEST_TIME - 1);
251 * Instantiates and returns the APCUIterator class.
253 * @param mixed $search
254 * A PCRE regular expression that matches against APC key names, either as a
255 * string for a single regular expression, or as an array of regular
256 * expressions. Or, optionally pass in NULL to skip the search.
258 * The desired format, as configured with one or more of the APC_ITER_*
260 * @param int $chunk_size
261 * The chunk size. Must be a value greater than 0. The default value is 100.
263 * The type to list. Either pass in APC_LIST_ACTIVE or APC_LIST_DELETED.
265 * @return \APCUIterator
267 protected function getIterator($search = NULL, $format = APC_ITER_ALL, $chunk_size = 100, $list = APC_LIST_ACTIVE) {
268 return new \APCUIterator($search, $format, $chunk_size, $list);