Skip to content
PHP Ecosystem
Explore

CacheInterface

API reference › yii › caching › CacheInterface

interfaceyii\caching\CacheInterface
ExtendsArrayAccess
Sourceframework/caching/CacheInterface.php
Implemented by 1 type

CacheInterface is the base interface for cache.

A data item can be stored in the cache by calling set() and be retrieved back later (in the same or different request) by get(). In both operations, a key identifying the data item is required. An expiration time and/or a dependency can also be specified when calling set(). If the data item expires or the dependency changes at the time of calling get(), the cache will return no data.

A typical usage pattern of cache is like the following:

$key = 'demo';
$data = $cache->get($key);
if ($data === false) {
// ...generate $data here...
$cache->set($key, $data, $duration, $dependency);
}

Because CacheInterface extends the ArrayAccess interface, it can be used like an array. For example,

$cache['foo'] = 'some data';
echo $cache['foo'];

For more details and usage information on Cache, see the guide article on caching.

MethodDescriptionDefined by
add() abstractStores a value identified by a key into cache if the cache does not contain this key.CacheInterface
buildKey() abstractBuilds a normalized cache key from a given key.CacheInterface
delete() abstractDeletes a value with the specified key from cache.CacheInterface
exists() abstractChecks whether a specified key exists in the cache.CacheInterface
flush() abstractDeletes all values from cache.CacheInterface
get() abstractRetrieves a value from cache with a specified key.CacheInterface
getOrSet() abstractMethod combines both set() and get() methods to retrieve value identified by a $key, or to store the result of $callable execution if there is no cache available for the $key.CacheInterface
multiAdd() abstractStores multiple items in cache. Each item contains a value identified by a key.CacheInterface
multiGet() abstractRetrieves multiple values from cache with the specified keys.CacheInterface
multiSet() abstractStores multiple items in cache. Each item contains a value identified by a key.CacheInterface
set() abstractStores a value identified by a key into cache.CacheInterface
abstract public function add(mixed $key, mixed $value, int $duration = 0, yii\caching\Dependency|null $dependency = null): bool

Stores a value identified by a key into cache if the cache does not contain this key.

Nothing will be done if the cache already contains the key.

Parameters

ParameterTypeDescription
$keymixedA key identifying the value to be cached. This can be a simple string or a complex data structure consisting of factors representing the key.
$valuemixedThe value to be cached
$durationintThe number of seconds in which the cached value will expire. 0 means never expire.
$dependencyDependency|nullDependency of the cached item. If the dependency changes, the corresponding value in the cache will be invalidated when it is fetched via get(). This parameter is ignored if serializer is false.

Returns

bool: Whether the value is successfully stored into cache

abstract public function buildKey(mixed $key): string

Builds a normalized cache key from a given key.

If the given key is a string containing alphanumeric characters only and no more than 32 characters, then the key will be returned back prefixed with keyPrefix. Otherwise, a normalized key is generated by serializing the given key, applying MD5 hashing, and prefixing with keyPrefix.

Parameters

ParameterTypeDescription
$keymixedThe key to be normalized

Returns

string: The generated cache key

abstract public function delete(mixed $key): bool

Deletes a value with the specified key from cache.

Parameters

ParameterTypeDescription
$keymixedA key identifying the value to be deleted from cache. This can be a simple string or a complex data structure consisting of factors representing the key.

Returns

bool: If no error happens during deletion

abstract public function exists(mixed $key): bool

Checks whether a specified key exists in the cache.

This can be faster than getting the value from the cache if the data is big. In case a cache does not support this feature natively, this method will try to simulate it but has no performance improvement over getting it. Note that this method does not check whether the dependency associated with the cached data, if there is any, has changed. So a call to get() may return false while exists returns true.

Parameters

ParameterTypeDescription
$keymixedA key identifying the cached value. This can be a simple string or a complex data structure consisting of factors representing the key.

Returns

bool: True if a value exists in cache, false if the value is not in the cache or expired.

abstract public function flush(): bool

Deletes all values from cache.

Be careful of performing this operation if the cache is shared among multiple applications.

Returns

bool: Whether the flush operation was successful.

abstract public function get(mixed $key): mixed

Retrieves a value from cache with a specified key.

Parameters

ParameterTypeDescription
$keymixedA key identifying the cached value. This can be a simple string or a complex data structure consisting of factors representing the key.

Returns

mixed: The value stored in cache, false if the value is not in the cache, expired, or the dependency associated with the cached data has changed.

abstract public function getOrSet(mixed $key, callable(): yii\caching\TResult|Closure(): yii\caching\TResult $callable, int|null $duration = null, yii\caching\Dependency|null $dependency = null): yii\caching\TResult

Method combines both set() and get() methods to retrieve value identified by a $key, or to store the result of $callable execution if there is no cache available for the $key.

Usage example:

public function getTopProducts($count = 10) {
$cache = $this->cache; // Could be Yii::$app->cache
return $cache->getOrSet(['top-n-products', 'n' => $count], function ($cache) use ($count) {
return Products::find()->mostPopular()->limit($count)->all();
}, 1000);
}

Parameters

ParameterTypeDescription
$keymixedA key identifying the value to be cached. This can be a simple string or a complex data structure consisting of factors representing the key.
$callablecallable(): yii\caching\TResult|Closure(): yii\caching\TResultThe callable or closure that will be used to generate a value to be cached. In case $callable returns false, the value will not be cached.
$durationint|nullDefault duration in seconds before the cache will expire. If not set, defaultDuration value will be used.
$dependencyDependency|nullDependency of the cached item. If the dependency changes, the corresponding value in the cache will be invalidated when it is fetched via get(). This parameter is ignored if serializer is false.

Returns

yii\caching\TResult: Result of $callable execution

abstract public function multiAdd(array $items, int $duration = 0, yii\caching\Dependency|null $dependency = null): array

Stores multiple items in cache. Each item contains a value identified by a key.

If the cache already contains such a key, the existing value and expiration time will be preserved.

Parameters

ParameterTypeDescription
$itemsarrayThe items to be cached, as key-value pairs.
$durationintDefault number of seconds in which the cached values will expire. 0 means never expire.
$dependencyDependency|nullDependency of the cached items. If the dependency changes, the corresponding values in the cache will be invalidated when it is fetched via get(). This parameter is ignored if serializer is false.

Returns

array: Array of failed keys

abstract public function multiGet(string[] $keys): array

Retrieves multiple values from cache with the specified keys.

Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time, which may improve the performance. In case a cache does not support this feature natively, this method will try to simulate it.

Parameters

ParameterTypeDescription
$keysstring[]List of string keys identifying the cached values

Returns

array: List of cached values corresponding to the specified keys. The array is returned in terms of (key, value) pairs. If a value is not cached or expired, the corresponding array value will be false.

abstract public function multiSet(array $items, int|null $duration = null, yii\caching\Dependency|null $dependency = null): array

Stores multiple items in cache. Each item contains a value identified by a key.

If the cache already contains such a key, the existing value and expiration time will be replaced with the new ones, respectively.

Parameters

ParameterTypeDescription
$itemsarrayThe items to be cached, as key-value pairs.
$durationint|nullDefault duration in seconds before the cache will expire. If not set, default defaultDuration value is used.
$dependencyDependency|nullDependency of the cached items. If the dependency changes, the corresponding values in the cache will be invalidated when it is fetched via get(). This parameter is ignored if serializer is false.

Returns

array: Array of failed keys

abstract public function set(mixed $key, mixed $value, int|null $duration = null, yii\caching\Dependency|null $dependency = null): bool

Stores a value identified by a key into cache.

If the cache already contains such a key, the existing value and expiration time will be replaced with the new ones, respectively.

Parameters

ParameterTypeDescription
$keymixedA key identifying the value to be cached. This can be a simple string or a complex data structure consisting of factors representing the key.
$valuemixedThe value to be cached
$durationint|nullDefault duration in seconds before the cache will expire. If not set, default defaultDuration value is used.
$dependencyDependency|nullDependency of the cached item. If the dependency changes, the corresponding value in the cache will be invalidated when it is fetched via get(). This parameter is ignored if serializer is false.

Returns

bool: Whether the value is successfully stored into cache