Drupal 8  8.0.2
Cache API

Data Structures

class  BackendChain
 
class  Cache
 
interface  CacheableDependencyInterface
 
class  CacheableMetadata
 
interface  CacheBackendInterface
 
class  CacheCollector
 
interface  CacheCollectorInterface
 
interface  CacheTagsChecksumInterface
 
interface  CacheTagsInvalidatorInterface
 
class  ChainedFastBackend
 
class  DatabaseBackend
 
class  MemoryBackend
 
class  NullBackend
 
class  PhpBackend
 

Functions

static cache ($bin= 'default')
 

Detailed Description

Information about the Drupal Cache API

Basics

Note: If not specified, all of the methods mentioned here belong to .

The Cache API is used to store data that takes a long time to compute. Caching can either be permanent or valid only for a certain timespan, and the cache can contain any type of data.

To use the Cache API:

Example:

$cid = 'mymodule_example:' . \Drupal::languageManager()->getCurrentLanguage()->getId();
$data = NULL;
if ($cache = \Drupal::cache()->get($cid)) {
$data = $cache->data;
}
else {
$data = my_module_complicated_calculation();
\Drupal::cache()->set($cid, $data);
}

Note the use of $data and $cache->data in the above example. Calls to ::cache()->get() return a record that contains the information stored by ::cache()->set() in the data property as well as additional meta information about the cached data. In order to make use of the cached data you can access it via $cache->data.

Cache bins

Cache storage is separated into "bins", each containing various cache items. Each bin can be configured separately; see Configuration.

When you request a cache object, you can specify the bin name in your call to ::cache(). Alternatively, you can request a bin by getting service "cache.nameofbin" from the container. The default bin is called "default", with service name "cache.default", it is used to store common and frequently used caches.

Other common cache bins are the following:

A module can define a cache bin by defining a service in its modulename.services.yml file as follows (substituting the desired name for "nameofbin"):

cache.nameofbin:
tags:
- { name: cache.bin }
factory: cache_factory:get
arguments: [nameofbin]

See the Services topic for more on defining services.

Delete operations

There are two ways to remove an item from the cache:

Use deletion if a cache item is no longer useful; for instance, if the item contains references to data that has been deleted. Use invalidation if the cached item may still be useful to some callers until it has been updated with fresh data. The fact that it was fresh a short while ago may often be sufficient.

Invalidation is particularly useful to protect against stampedes. Rather than having multiple concurrent requests updating the same cache item when it expires or is deleted, there can be one request updating the cache, while the other requests can proceed using the stale value. As soon as the cache item has been updated, all future requests will use the updated value.

Cache Tags

The fourth argument of the set() method can be used to specify cache tags, which are used to identify which data is included in each cache item. A cache item can have multiple cache tags (an array of cache tags), and each cache tag is a string. The convention is to generate cache tags of the form [prefix]:[suffix]. Usually, you'll want to associate the cache tags of entities, or entity listings. You won't have to manually construct cache tags for them — just get their cache tags via ::getCacheTags() and ::getListCacheTags(). Data that has been tagged can be invalidated as a group: no matter the Cache ID (cid) of the cache item, no matter in which cache bin a cache item lives; as long as it is tagged with a certain cache tag, it will be invalidated.

Because of that, cache tags are a solution to the cache invalidation problem:

A typical scenario: a user has modified a node that appears in two views, three blocks and on twelve pages. Without cache tags, we couldn't possibly know which cache items to invalidate, so we'd have to invalidate everything: we had to sacrifice effectiveness to achieve correctness. With cache tags, we can have both.

Example:

// A cache item with nodes, users, and some custom module data.
$tags = array(
'my_custom_tag',
'node:1',
'node:3',
'user:7',
);
\Drupal::cache()->set($cid, $data, CacheBackendInterface::CACHE_PERMANENT, $tags);
// Invalidate all cache items with certain tags.

Drupal is a content management system, so naturally you want changes to your content to be reflected everywhere, immediately. That's why we made sure that every entity type in Drupal 8 automatically has support for cache tags: when you save an entity, you can be sure that the cache items that have the corresponding cache tags will be invalidated. This also is the case when you define your own entity types: you'll get the exact same cache tag invalidation as any of the built-in entity types, with the ability to override any of the default behavior if needed. See ::getCacheTags(), ::getListCacheTags(), ::invalidateTagsOnSave() and ::invalidateTagsOnDelete().

Translation string sharing and context

Some computed data depends on contextual data, such as the user roles of the logged-in user who is viewing a page, the language the page is being rendered in, the theme being used, etc. When caching the output of such a calculation, you must cache each variation separately, along with information about which variation of the contextual data was used in the calculatation. The next time the computed data is needed, if the context matches that for an existing cached data set, the cached data can be reused; if no context matches, a new data set can be calculated and cached for later use.

Cache contexts are services tagged with 'cache.context', whose classes implement . See https://www.drupal.org/developing/api/8/cache/contexts for more information on cache contexts, including a list of the contexts that exist in Drupal core, and information on how to define your own contexts. See the Services and the Dependency Injection Container topic for more information about services.

Typically, the cache context is specified as part of the #cache property of a render array; see the Caching section of the Render API overview topic for details.

Configuration

By default cached data is stored in the database. This can be configured though so that all cached data, or that of an individual cache bin, uses a different cache backend, such as APCu or Memcache, for storage.

In a settings.php file, you can override the service used for a particular cache bin. For example, if your service implementation of was called cache.custom, the following line would make Drupal use it for the 'cache_render' bin:

$settings['cache']['bins']['render'] = 'cache.custom';

Additionally, you can register your cache implementation to be used by default for all cache bins with:

$settings['cache']['default'] = 'cache.custom';

Finally, you can chain multiple cache backends together, see and .

See Also
https://www.drupal.org/node/1884796

Function Documentation

static cache (   $bin = 'default')
static

Returns the requested cache bin.

Parameters
string$bin(optional) The cache bin for which the cache object should be returned, defaults to 'default'.
Returns
The cache object associated with the specified bin.

Referenced by FormController\__construct(), TypeLinkManager\__construct(), Internal\__construct(), PermissionsHashGenerator\__construct(), CachedStorage\__construct(), RelationLinkManager\__construct(), TwigPhpStorageCache\__construct(), ThemeRegistry\__construct(), FileCache\__construct(), ThemeInitialization\__construct(), RoutePreloader\__construct(), PageCache\__construct(), AssetResolver\__construct(), LocaleLookup\__construct(), LocaleTranslation\__construct(), DbUpdateController\__construct(), AliasManager\__construct(), RouteProvider\__construct(), CacheCollector\__construct(), Token\__construct(), Registry\__construct(), FilesystemLoader\addPath(), CacheTestBase\assertCacheRemoved(), BookManager\bookSubtreeData(), Registry\build(), AliasManager\cacheClear(), CachePluginBase\cacheGet(), CachePluginBase\cacheSet(), CacheTestBase\checkCacheExists(), CacheCollector\clear(), ConfigFactory\clearStaticCache(), CachedStorageTest\delete(), MemoryBackend\delete(), CachedStorage\delete(), FileCache\delete(), MemoryBackend\deleteAll(), CachedStorage\deleteAll(), State\deleteMultiple(), LocaleProjectStorage\deleteMultiple(), MemoryBackend\deleteMultiple(), BookManager\doBookTreeBuild(), ConfigFactory\doLoadMultiple(), ThemeRegistryLoader\findTemplate(), PermissionsHashGenerator\generate(), Internal\generateFormatTagsSetting(), MemoryBackend\get(), Registry\get(), PageCache\get(), ThemeInitialization\getActiveThemeByName(), AliasManager\getAliasByPath(), LocaleProjectStorage\getAll(), SourcePluginBase\getCache(), ConfigFactory\getConfigCacheKeys(), AssetResolver\getCssAssets(), ExposedFormCache\getForm(), Token\getInfo(), AssetResolver\getJsAssets(), CKEditor\getLangcodes(), MemoryBackend\getMultiple(), State\getMultiple(), LocaleProjectStorage\getMultiple(), FileCache\getMultiple(), RelationLinkManager\getRelations(), RouteProvider\getRouteCollectionForRequest(), LocaleTranslation\getStringTranslation(), TwigPhpStorageCache\getTimestamp(), TypeLinkManager\getTypes(), hook_image_style_flush(), CachedStorageTest\insert(), MemoryBackend\invalidate(), MemoryBackend\invalidateAll(), CacheCollector\invalidateCache(), MemoryBackend\invalidateMultiple(), MemoryBackend\invalidateTags(), CacheCollector\lazyLoadCache(), menu_cache_clear_all(), ConfigFactory\onConfigDelete(), ConfigFactory\onConfigSave(), RoutePreloader\onRequest(), RouteProvider\preLoadRoutes(), ConfigFactory\propagateConfigOverrideCacheability(), GroupwiseMax\query(), CachedStorageTest\read(), CachedStorage\read(), CachedStorage\readMultiple(), MemoryBackend\removeBin(), PhpBackend\removeBin(), CachedStorage\rename(), ConfigFactory\rename(), ExposedFormCache\reset(), MemoryBackend\reset(), ConfigFactory\reset(), State\resetCache(), LocaleProjectStorage\resetCache(), DbUpdateController\selection(), State\set(), MemoryBackend\set(), FileCache\set(), PageCache\set(), Registry\setCache(), FormState\setCached(), State\setMultiple(), LocaleProjectStorage\setMultiple(), LocaleTranslationTest\setUp(), RoutePreloaderTest\setUp(), ElementInfoManagerTest\setUp(), RegistryTest\setUp(), MailManagerTest\setUp(), AliasManagerTest\setUp(), AssetResolverTest\setUp(), LocaleLookupTest\setUp(), MenuActiveTrailTest\setUp(), LibraryDiscoveryCollectorTest\setUp(), PermissionsHashGeneratorTest\setUp(), RouteProviderTest\setUp(), DbDumpTest\setUp(), TokenTest\setUp(), SqlContentEntityStorageTest\setUp(), FormTestBase\setUp(), SqlContentEntityStorageTest\setUpEntityStorage(), MailManagerTest\setUpMailManager(), GroupwiseMax\submitOptionsForm(), BlockTest\testBlockCacheTags(), DrupalTest\testCache(), AliasManagerTest\testCacheClear(), CacheTest\testCacheData(), RouteProviderTest\testCandidateOutlines(), LocaleTranslationTest\testDestruct(), LibraryDiscoveryCollectorTest\testDestruct(), RouteProviderTest\testEmptyPathCandidatesOutlines(), FieldAttachOtherTest\testEntityCache(), ShortcutCacheTagsTest\testEntityCreation(), ItemCacheTagsTest\testEntityCreation(), EntityDisplayTest\testEntityDisplayInvalidateCacheTags(), RouteProviderTest\testExactPathMatch(), PermissionsHashGeneratorTest\testGenerateNoCache(), PermissionsHashGeneratorTest\testGeneratePersistentCache(), PermissionsHashGeneratorTest\testGenerateStaticCache(), AliasManagerTest\testGetAliasByPathCachedMatch(), AliasManagerTest\testGetAliasByPathCachedMissLanguage(), AliasManagerTest\testGetAliasByPathCachedMissNoAlias(), AliasManagerTest\testGetAliasByPathMatch(), AliasManagerTest\testGetAliasByPathNoMatch(), AliasManagerTest\testGetAliasByPathUncachedMissNoAlias(), AliasManagerTest\testGetAliasByPathUncachedMissWithAlias(), AssetResolverTest\testGetCssAssets(), TokenTest\testGetInfo(), ElementInfoManagerTest\testGetInfoElementPlugin(), ElementInfoManagerTest\testGetInfoProperty(), AssetResolverTest\testGetJsAssets(), RouteProviderTest\testGetRoutesByPatternWithLongPatterns(), RouteProviderTest\testGetRoutesPaged(), SqlContentEntityStorageTest\testHasData(), SqlContentEntityStorageTest\testLoadMultipleNoPersistentCache(), SqlContentEntityStorageTest\testLoadMultiplePersistentCached(), SqlContentEntityStorageTest\testLoadMultiplePersistentCacheMiss(), RegistryTest\testMultipleSubThemes(), SqlContentEntityStorageTest\testOnEntityTypeCreate(), RouteProviderTest\testOutlinePathMatch(), RouteProviderTest\testOutlinePathMatchDefaults(), RouteProviderTest\testOutlinePathMatchDefaultsCollision(), RouteProviderTest\testOutlinePathMatchDefaultsCollision2(), RouteProviderTest\testOutlinePathMatchDefaultsCollision3(), RouteProviderTest\testOutlinePathMatchTrailingSlash(), RouteProviderTest\testOutlinePathMatchZero(), RouteProviderTest\testOutlinePathNoMatch(), PageCacheTest\testPageCacheTags(), PageCacheTest\testPageCacheTagsIndependentFromCacheabilityHeaders(), PathAliasTest\testPathCache(), RegistryTest\testRaceCondition(), LibraryDiscoveryCollectorTest\testResolveCacheMiss(), LocaleLookupTest\testResolveCacheMissNoTranslation(), LocaleLookupTest\testResolveCacheMissWithFallback(), LocaleLookupTest\testResolveCacheMissWithoutFallback(), LocaleLookupTest\testResolveCacheMissWithPersist(), RouteProviderTest\testRouteByName(), DbDumpTest\testScriptLoad(), DrupalKernelSiteTest\testServicesYml(), StableTemplateOverrideTest\testStableTemplateOverrides(), CacheTest\testSubqueryStringCache(), RegistryTest\testSuggestionPreprocessFunctions(), UninstallTest\testUninstallPage(), EntityLanguageTestBase\toggleFieldTranslatability(), CachedStorageTest\update(), ThemeRegistry\updateCache(), CacheCollector\updateCache(), PageCacheTagsTestBase\verifyPageCache(), EntityCacheTagsTestBase\verifyRenderCache(), TwigPhpStorageCache\write(), CachedStorage\write(), TypeLinkManager\writeCache(), RelationLinkManager\writeCache(), and AliasManager\writeCache().