Cache
API reference › yii › caching › Cache
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 cachesetValue(): store the value with a key into cacheaddValue(): store the value only if the cache does not have this key beforedeleteValue(): delete the value with the specified key from cacheflushValues(): delete all values from cache
For more details and usage information on Cache, see the guide article on caching.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$defaultDuration | int | Default duration in seconds before a cache entry will expire. Default: 0. Available since 2.0.11. | Cache |
$keyPrefix | string | A string prefixed to every cache key so that it is unique globally in the whole cache storage. Default: null. | Cache |
$serializer | array| | The functions used to serialize and unserialize cached data. Default: null. | Cache |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
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\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
buildKey() | Builds a normalized cache key from a given key. | Cache |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
delete() | Deletes a value with the specified key from cache. | Cache |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
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\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
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\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
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\ |
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\ |
set() | Stores a value identified by a key into cache. | Cache |
trigger() | Triggers an event. | yii\ |
addValue() protected abstract | Stores a value identified by a key into cache if the cache does not contain this key. | Cache |
addValues() protected | Adds multiple key-value pairs to cache. | Cache |
deleteValue() protected abstract | 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. | Cache |
flushValues() protected abstract | Deletes all values from cache. | Cache |
getValue() protected abstract | Retrieves a value from cache with a specified key. | Cache |
getValues() protected | Retrieves multiple values from cache with the specified keys. | Cache |
setValue() protected abstract | Stores a value identified by a key in cache. | Cache |
setValues() protected | Stores multiple key-value pairs in cache. | Cache |
Property details
Section titled “Property details”$defaultDuration
Section titled “$defaultDuration ”public int $defaultDuration = 0Default 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
$keyPrefix
Section titled “$keyPrefix ”public string $keyPrefix = nullA 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.
$serializer
Section titled “$serializer ”public array|null|false $serializer = nullThe 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.
Method details
Section titled “Method details”add()
Section titled “add() ”public function add(mixed $key, mixed $value, int $duration = 0, yii\caching\Dependency|null $dependency = null): boolStores 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
| Parameter | Type | Description |
|---|---|---|
$key | mixed | A key identifying the value to be cached. This can be a simple string or a complex data structure consisting of factors representing the key. |
$value | mixed | The value to be cached |
$duration | int | The number of seconds in which the cached value will expire. 0 means never expire. |
$dependency | Dependency| | Dependency 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
buildKey()
Section titled “buildKey() ”public function buildKey(mixed $key): stringBuilds 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
| Parameter | Type | Description |
|---|---|---|
$key | mixed | The key to be normalized |
Returns
string: The generated cache key
delete()
Section titled “delete() ”public function delete(mixed $key): boolDeletes a value with the specified key from cache.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | mixed | A 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
exists()
Section titled “exists() ”public function exists(mixed $key): boolChecks 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
| Parameter | Type | Description |
|---|---|---|
$key | mixed | A 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.
flush()
Section titled “flush() ”public function flush(): boolDeletes 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.
get()
Section titled “get() ”public function get(mixed $key): mixedRetrieves a value from cache with a specified key.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | mixed | A 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.
getOrSet()
Section titled “getOrSet() ”public function getOrSet(mixed $key, callable|Closure $callable, int|null $duration = null, yii\caching\Dependency|null $dependency = null): mixedMethod 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
| Parameter | Type | Description |
|---|---|---|
$key | mixed | A key identifying the value to be cached. This can be a simple string or a complex data structure consisting of factors representing the key. |
$callable | callable|Closure | The 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. |
$duration | int| | Default duration in seconds before the cache will expire. If not set, $defaultDuration value will be used. |
$dependency | Dependency| | Dependency 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
init()
Section titled “init() ”public function init(): mixedInitializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
Returns
mixed
multiAdd()
Section titled “multiAdd() ”public function multiAdd(array $items, int $duration = 0, yii\caching\Dependency|null $dependency = null): arrayStores 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
| Parameter | Type | Description |
|---|---|---|
$items | array | The items to be cached, as key-value pairs. |
$duration | int | Default number of seconds in which the cached values will expire. 0 means never expire. |
$dependency | Dependency| | Dependency 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
multiGet()
Section titled “multiGet() ”public function multiGet(string[] $keys): arrayRetrieves 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
| Parameter | Type | Description |
|---|---|---|
$keys | string[] | 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
multiSet()
Section titled “multiSet() ”public function multiSet(array $items, int|null $duration = null, yii\caching\Dependency|null $dependency = null): arrayStores 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
| Parameter | Type | Description |
|---|---|---|
$items | array | The items to be cached, as key-value pairs. |
$duration | int| | Default duration in seconds before the cache will expire. If not set, default $defaultDuration value is used. |
$dependency | Dependency| | Dependency 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
offsetExists()
Section titled “offsetExists() ”public function offsetExists(string $key): boolReturns whether there is a cache entry with a specified key.
This method is required by the interface ArrayAccess.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | A key identifying the cached value |
Returns
bool
offsetGet()
Section titled “offsetGet() ”public function offsetGet(string $key): mixedRetrieves the value from cache with a specified key.
This method is required by the interface ArrayAccess.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | A key identifying the cached value |
Returns
mixed: The value stored in cache, false if the value is not in the cache or expired.
offsetSet()
Section titled “offsetSet() ”public function offsetSet(string $key, mixed $value): mixedStores 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
| Parameter | Type | Description |
|---|---|---|
$key | string | The key identifying the value to be cached |
$value | mixed | The value to be cached |
Returns
mixed
offsetUnset()
Section titled “offsetUnset() ”public function offsetUnset(string $key): mixedDeletes the value with the specified key from cache
This method is required by the interface ArrayAccess.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | The key of the value to be deleted |
Returns
mixed
set()
Section titled “set() ”public function set(mixed $key, mixed $value, int|null $duration = null, yii\caching\Dependency|null $dependency = null): boolStores 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
| Parameter | Type | Description |
|---|---|---|
$key | mixed | A key identifying the value to be cached. This can be a simple string or a complex data structure consisting of factors representing the key. |
$value | mixed | The value to be cached |
$duration | int| | Default duration in seconds before the cache will expire. If not set, default $defaultDuration value is used. |
$dependency | Dependency| | Dependency 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
addValue()
Section titled “addValue() ”abstract protected function addValue(string $key, mixed $value, int $duration): boolStores 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
| Parameter | Type | Description |
|---|---|---|
$key | string | The key identifying the value to be cached |
$value | mixed | The value to be cached. Most often it’s a string. If you have disabled $serializer, it could be something else. |
$duration | int | The 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
addValues()
Section titled “addValues() ”protected function addValues(array $data, int $duration): arrayAdds 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
| Parameter | Type | Description |
|---|---|---|
$data | array | Array where key corresponds to cache key while value is the value stored. |
$duration | int | The number of seconds in which the cached values will expire. 0 means never expire. |
Returns
array: Array of failed keys
deleteValue()
Section titled “deleteValue() ”abstract protected function deleteValue(string $key): boolDeletes 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
| Parameter | Type | Description |
|---|---|---|
$key | string | The key of the value to be deleted |
Returns
bool: If no error happens during deletion
flushValues()
Section titled “flushValues() ”abstract protected function flushValues(): boolDeletes all values from cache.
Child classes may implement this method to realize the flush operation.
Returns
bool: Whether the flush operation was successful.
getValue()
Section titled “getValue() ”abstract protected function getValue(string $key): mixed|falseRetrieves 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
| Parameter | Type | Description |
|---|---|---|
$key | string | A 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.
getValues()
Section titled “getValues() ”protected function getValues(array $keys): arrayRetrieves 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
| Parameter | Type | Description |
|---|---|---|
$keys | array | A list of keys identifying the cached values |
Returns
array: A list of cached values indexed by the keys
setValue()
Section titled “setValue() ”abstract protected function setValue(string $key, mixed $value, int $duration): boolStores 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
| Parameter | Type | Description |
|---|---|---|
$key | string | The key identifying the value to be cached |
$value | mixed | The value to be cached. Most often it’s a string. If you have disabled $serializer, it could be something else. |
$duration | int | The 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
setValues()
Section titled “setValues() ”protected function setValues(array $data, int $duration): arrayStores 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
| Parameter | Type | Description |
|---|---|---|
$data | array | Array where key corresponds to cache key while value is the value stored |
$duration | int | The number of seconds in which the cached values will expire. 0 means never expire. |
Returns
array: Array of failed keys