Civi::cache() is the simplest way to access the cache, automatically
using the default cache type (described below). The
CRM_Utils_Cache_Interface class lays out the methods for saving and
retrieving cached items.
`Civi::cache()` is the simplest way to access the cache, automatically using the default cache type (described below). The `CRM_Utils_Cache_Interface` class lays out the methods for saving and retrieving cached items.
### Methods
#### Set a cache value
<divclass="code panel"style="border-width: 1px;">
<divclass="codeContent panelContent">
* Set a cache value
```php
Civi::cache()->set('mykey', 'myvalue');
```
</div>
</div>
#### Get a cached value
<divclass="code panel"style="border-width: 1px;">
<divclass="codeContent panelContent">
* Get a cached value
```php
Civi::cache()->get('mykey'); // returns the value, or NULL if not set
```
</div>
</div>
#### Delete a cached value
<divclass="code panel"style="border-width: 1px;">
<divclass="codeContent panelContent">
* Delete a cached value
```php
Civi::cache()->delete('mykey');
```
</div>
</div>
#### Flush the entire cache
<divclass="code panel"style="border-width: 1px;">
<divclass="codeContent panelContent">
* Flush the entire cache
```php
Civi::cache()->flush();
</div>
</div>
```
### Example
<divclass="code panel"style="border-width: 1px;">
<divclass="codeContent panelContent">
/**
* Finds the magic number, selecting one if necessary.
*
* @return int $magicNumber
* a magic number between 1 and 100
*/
function findMagicNumber() {
$magicNumber = Civi::cache()->get('magicNumber');
if (!$magicNumber) {
$magicNumber = rand(1,100);
Civi::cache()->set('magicNumber', $magicNumber);
}
return $magicNumber;
}
</div>
</div>
```php
/**
* Finds the magic number, selecting one if necessary.
*
* @return int $magicNumber
* a magic number between 1 and 100
*/
functionfindMagicNumber(){
$magicNumber=Civi::cache()->get('magicNumber');
if(!$magicNumber){
$magicNumber=rand(1,100);
Civi::cache()->set('magicNumber',$magicNumber);
}
return$magicNumber;
}
```
## Cache types
This is selected in civicrm.settings.php (at or near line 276), where
CIVICRM_DB_CACHE_CLASS is defined.
#### ArrayCache
This is the default, using an in-memory array.
#### Memcache
This is for the PHP Memcache extension.
#### Memcached
This is selected in `civicrm.settings.php`, where `CIVICRM_DB_CACHE_CLASS` is defined.
This is for the PHP Memcached extension.
* "ArrayCache" - This is the default, using an in-memory array.
#### APCcache
* "Memcache" - This is for the PHP Memcache extension.
This is for the PHP APC extension.
* "Memcached" - This is for the PHP Memcached extension.