Skip to content
PHP Ecosystem
Explore

Cache

API reference › yii › caching › Cache

abstract classyii\caching\Cache
Extendsyii\base\Component » yii\base\BaseObject
ImplementsCacheInterface, yii\base\Configurable
Since2.0
Sourceframework/caching/Cache.php
7 subclasses

Cache is the base class for cache classes supporting different cache storage implementations.

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 Cache implements the ArrayAccess interface, it can be used like an array. For example,

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

Derived classes should implement the following methods which do the actual cache storage operations:

  • getValue(): retrieve the value with a key (if any) from cache
  • setValue(): store the value with a key into cache
  • addValue(): store the value only if the cache does not have this key before
  • deleteValue(): delete the value with the specified key from cache
  • flushValues(): delete all values from cache

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

PropertyTypeDescriptionDefined by
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$defaultDurationintDefault duration in seconds before a cache entry will expire. Default: 0. Available since 2.0.11.Cache
$keyPrefixstringA string prefixed to every cache key so that it is unique globally in the whole cache storage. Default: null.Cache
$serializerarray|null|falseThe functions used to serialize and unserialize cached data. Default: null.Cache
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
add()Stores a value identified by a key into cache if the cache does not contain this key.Cache
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
buildKey()Builds a normalized cache key from a given key.Cache
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
delete()Deletes a value with the specified key from cache.Cache
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
exists()Checks whether a specified key exists in the cache.Cache
flush()Deletes all values from cache.Cache
get()Retrieves a value from cache with a specified key.Cache
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getOrSet()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.Cache
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Initializes the object.Cache
multiAdd()Stores multiple items in cache. Each item contains a value identified by a key.Cache
multiGet()Retrieves multiple values from cache with the specified keys.Cache
multiSet()Stores multiple items in cache. Each item contains a value identified by a key.Cache
off()Detaches an existing event handler from this component.yii\base\Component
offsetExists()Returns whether there is a cache entry with a specified key.Cache
offsetGet()Retrieves the value from cache with a specified key.Cache
offsetSet()Stores the value identified by a key into cache.Cache
offsetUnset()Deletes the value with the specified key from cache This method is required by the interface ArrayAccess.Cache
on()Attaches an event handler to an event.yii\base\Component
set()Stores a value identified by a key into cache.Cache
trigger()Triggers an event.yii\base\Component
addValue() protected abstractStores a value identified by a key into cache if the cache does not contain this key.Cache
addValues() protectedAdds multiple key-value pairs to cache.Cache
deleteValue() protected abstractDeletes a value with the specified key from cache This method should be implemented by child classes to delete the data from actual cache storage.Cache
flushValues() protected abstractDeletes all values from cache.Cache
getValue() protected abstractRetrieves a value from cache with a specified key.Cache
getValues() protectedRetrieves multiple values from cache with the specified keys.Cache
setValue() protected abstractStores a value identified by a key in cache.Cache
setValues() protectedStores multiple key-value pairs in cache.Cache
public int $defaultDuration = 0

Default duration in seconds before a cache entry will expire.

Default value is 0, meaning infinity. This value is used by set() if the duration is not explicitly given.

Since

2.0.11

public string $keyPrefix = null

A string prefixed to every cache key so that it is unique globally in the whole cache storage.

It is recommended that you set a unique cache key prefix for each application if the same cache storage is being used by different applications.

To ensure interoperability, only alphanumeric characters should be used.

public array|null|false $serializer = null

The functions used to serialize and unserialize cached data.

Defaults to null, meaning using the default PHP serialize() and unserialize() functions. If you want to use some more efficient serializer (e.g. igbinary), you may configure this property with a two-element array. The first element specifies the serialization function, and the second the deserialization function. If this property is set false, data will be directly sent to and retrieved from the underlying cache component without any serialization or deserialization. You should not turn off serialization if you are using cache dependency, because it relies on data serialization. Also, some implementations of the cache can not correctly save and retrieve data different from a string type.

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

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

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

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.

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.

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.

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

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 () 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|ClosureThe callable or closure that will be used to generate a value to be cached. If you use $callable that can return false, then keep in mind that getOrSet() may work inefficiently because the Cache::get() method uses false return value to indicate the data item is not found in the cache. Thus, caching of false value will lead to unnecessary internal calls.
$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

mixed: Result of $callable execution

Since

2.0.11

public function init(): mixed

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

Returns

mixed

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

Since

2.0.7

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.

Since

2.0.7

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

Since

2.0.7

public function offsetExists(string $key): bool

Returns whether there is a cache entry with a specified key.

This method is required by the interface ArrayAccess.

Parameters

ParameterTypeDescription
$keystringA key identifying the cached value

Returns

bool

public function offsetGet(string $key): mixed

Retrieves the value from cache with a specified key.

This method is required by the interface ArrayAccess.

Parameters

ParameterTypeDescription
$keystringA key identifying the cached value

Returns

mixed: The value stored in cache, false if the value is not in the cache or expired.

public function offsetSet(string $key, mixed $value): mixed

Stores the value identified by a key into cache.

If the cache already contains such a key, the existing value will be replaced with the new ones. To add expiration and dependencies, use the set() method. This method is required by the interface ArrayAccess.

Parameters

ParameterTypeDescription
$keystringThe key identifying the value to be cached
$valuemixedThe value to be cached

Returns

mixed

public function offsetUnset(string $key): mixed

Deletes the value with the specified key from cache This method is required by the interface ArrayAccess.

Parameters

ParameterTypeDescription
$keystringThe key of the value to be deleted

Returns

mixed

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

abstract protected function addValue(string $key, mixed $value, int $duration): bool

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

This method should be implemented by child classes to store the data in specific cache storage.

Parameters

ParameterTypeDescription
$keystringThe key identifying the value to be cached
$valuemixedThe value to be cached. Most often it’s a string. If you have disabled $serializer, it could be something else.
$durationintThe number of seconds in which the cached value will expire. 0 means never expire.

Returns

bool: True if the value is successfully stored into cache, false otherwise

protected function addValues(array $data, int $duration): array

Adds multiple key-value pairs to cache.

The default implementation calls addValue() multiple times add values one by one. If the underlying cache storage supports multi-add, this method should be overridden to exploit that feature.

Parameters

ParameterTypeDescription
$dataarrayArray where key corresponds to cache key while value is the value stored.
$durationintThe number of seconds in which the cached values will expire. 0 means never expire.

Returns

array: Array of failed keys

abstract protected function deleteValue(string $key): bool

Deletes a value with the specified key from cache This method should be implemented by child classes to delete the data from actual cache storage.

Parameters

ParameterTypeDescription
$keystringThe key of the value to be deleted

Returns

bool: If no error happens during deletion

abstract protected function flushValues(): bool

Deletes all values from cache.

Child classes may implement this method to realize the flush operation.

Returns

bool: Whether the flush operation was successful.

abstract protected function getValue(string $key): mixed|false

Retrieves a value from cache with a specified key.

This method should be implemented by child classes to retrieve the data from specific cache storage.

Parameters

ParameterTypeDescription
$keystringA unique key identifying the cached value

Returns

mixed|false: The value stored in cache, false if the value is not in the cache or expired. Most often value is a string. If you have disabled $serializer, it could be something else.

protected function getValues(array $keys): array

Retrieves multiple values from cache with the specified keys.

The default implementation calls getValue() multiple times to retrieve the cached values one by one. If the underlying cache storage supports multiget, this method should be overridden to exploit that feature.

Parameters

ParameterTypeDescription
$keysarrayA list of keys identifying the cached values

Returns

array: A list of cached values indexed by the keys

abstract protected function setValue(string $key, mixed $value, int $duration): bool

Stores a value identified by a key in cache.

This method should be implemented by child classes to store the data in specific cache storage.

Parameters

ParameterTypeDescription
$keystringThe key identifying the value to be cached
$valuemixedThe value to be cached. Most often it’s a string. If you have disabled $serializer, it could be something else.
$durationintThe number of seconds in which the cached value will expire. 0 means never expire.

Returns

bool: True if the value is successfully stored into cache, false otherwise

protected function setValues(array $data, int $duration): array

Stores multiple key-value pairs in cache.

The default implementation calls setValue() multiple times store values one by one. If the underlying cache storage supports multi-set, this method should be overridden to exploit that feature.

Parameters

ParameterTypeDescription
$dataarrayArray where key corresponds to cache key while value is the value stored
$durationintThe number of seconds in which the cached values will expire. 0 means never expire.

Returns

array: Array of failed keys