CodeIgniter features wrappers around some of the most popular forms of fast and dynamic caching. All but file-based caching have specific server requirements, and a Fatal Exception will be thrown if server requirements are not met.
The following example shows a common usage pattern within your controllers.
<?php
if (! $foo = cache('foo')) {
echo 'Saving to the cache!<br>';
$foo = 'foobarbaz!';
// Save into the cache for 5 minutes
cache()->save('foo', $foo, 300);
}
echo $foo;You can grab an instance of the cache engine directly through the global function service():
<?php
$cache = service('cache');
$foo = $cache->get('foo');All configuration for the cache engine is done in app/Config/Cache.php. In that file, the following items are available.
This is the name of the handler that should be used as the primary handler when starting up the engine. Available names are: apcu, dummy, file, memcached, redis, predis, wincache.
In the case that the first choice $handler is not available, this is the next cache handler to load. This is commonly the File handler since the file system is always available, but may not fit more complex, multi-server setups.
If you have more than one application using the same cache storage, you can add a custom prefix string here that is prepended to all key names.
The default number of seconds to save items when none is specified.
WARNING: This is not used by framework handlers where 60 seconds is hard-coded, but may be useful to projects and modules. This will replace the hard-coded value in a future release.
A string of characters that are not allowed in cache keys or tags. Handlers throw an InvalidArgumentException when a key contains one of them. The default, {}()/\@:, is required for PSR-6 compliance.
Relaxing $reservedCharacters relaxes key validation for every cache handler. The File handler still rejects /, \ and null bytes in the resulting file name, so a cache key cannot point outside the cache directory. The characters left in $reservedCharacters still keep keys from being interpreted differently by a handler or by the file system.
On Windows, keep : reserved: it separates an NTFS alternate data stream, so a key such as file:stream refers to a stream of a file in the cache directory rather than to a new cache item.
Do not use unvalidated user input directly as a cache key. Build keys from identifiers with a controlled format, or hash the input:
$key = 'search_' . hash('sha256', $userInput);This is an array of settings specific to the File handler to determine how it should save the cache files.
Dot-leading cache keys are supported by the File handler: they are reported by getCacheInfo(), matched by deleteMatching(), and removed by clean() / cache:clear. The .htaccess protection file is never deleted by deleteMatching(), and the protection files (.htaccess, index.html, index.htm, index.php, web.config) are kept by clean(); any other dot-leading file in the cache directory is affected. See the notes below deleteMatching(), clean() and getCacheInfo().
This is an array of servers that will be used when using the Memcached handler.
The settings for the Redis server that you wish to use when using the Redis and Predis handlers.
CodeIgniter ships with several commands that are available from the command line to help you work with Cache. These tools are not required to use the Cache driver, but might help you.
Clears the current system caches:
php spark cache:clearShows file cache information in the current system:
php spark cache:info!!! note "Note" This command only supports the File cache handler.
- Returns:
trueif supported,falseif not - Return type:
bool
-
Parameters
- $key
stringCache item name
- $key
-
Returns: Item value or
nullif not found -
Return type:
mixed
This method will attempt to fetch an item from the cache store. If the item does not exist, the method will return null.
Example:
<?php
$foo = $cache->get('my_cached_item');-
Parameters
- $key
stringCache item name - $ttl
intTime to live in seconds - $callback
ClosureCallback to invoke when the cache item returns null
- $key
-
Returns: The value of the cache item
-
Return type:
mixed
Gets an item from the cache. If null was returned, this will invoke the callback and save the result. Either way, this will return the value.
-
Parameters
- $key
stringCache item name - $data
mixedthe data to save - $ttl
intTime To Live, in seconds (default 60)
- $key
-
Returns:
trueon success,falseon failure -
Return type:
bool
This method will save an item to the cache store. If saving fails, the method will return false.
Example:
<?php
$cache->save('cache_item_id', 'data_to_cache');-
Parameters
- $key
stringname of cached item
- $key
-
Returns:
trueon success,falseon failure -
Return type:
bool
This method will delete a specific item from the cache store. If item deletion fails, the method will return false.
Example:
<?php
$cache->delete('cache_item_id');-
Parameters
- $pattern
stringglob-style pattern to match cached item keys
- $pattern
-
Returns: number of deleted items
-
Return type:
integer
This method will delete multiple items from the cache store at once by matching their keys against a glob-style pattern. It will return the total number of deleted items.
!!! important "Important" This method is only implemented for the File, Redis and Predis handlers. Due to limitations, it couldn't be implemented for the Memcached and Wincache handlers.
!!! note "Note"
With the File handler, the pattern is matched against cache file names only and cannot match files in subdirectories. A pattern containing a forward slash (/) therefore never matches. A cache entry whose key begins with a period (a dot-leading file name) is matched by patterns like any other entry, but the .htaccess protection file is never deleted. Any other dot-leading file in the cache directory (for example .gitignore or .env) is matched as well.
Example:
<?php
$cache->deleteMatching('prefix_*'); // deletes all items of which keys start with "prefix_"
$cache->deleteMatching('*_suffix'); // deletes all items of which keys end with "_suffix"For more information on glob-style syntax, please see Glob (programming).
-
Parameters
- $key
stringCache ID - $offset
intStep/value to add
- $key
-
Returns: New value on success,
falseon failure -
Return type:
mixed
Performs atomic incrementation of a raw stored value.
Example:
<?php
// 'iterator' has a value of 2
$cache->increment('iterator'); // 'iterator' is now 3
$cache->increment('iterator', 3); // 'iterator' is now 6-
Parameters
- $key
stringCache ID - $offset
intStep/value to reduce by
- $key
-
Returns: New value on success,
falseon failure -
Return type:
mixed
Performs atomic decrementation of a raw stored value.
Example:
<?php
// 'iterator' has a value of 6
$cache->decrement('iterator'); // 'iterator' is now 5
$cache->decrement('iterator', 2); // 'iterator' is now 3!!! important "Important"
Memcached counters are unsigned and saturate at 0 instead of going negative. Decrementing a key that does not yet exist initializes it to 0 (rather than -$offset, as the File, Redis, and Predis handlers do), and decrementing an existing counter below 0 clamps it at 0.
- Returns:
trueon success,falseon failure - Return type:
bool
This method will 'clean' the entire cache. If the deletion of the cache files fails, the method will return false.
Example:
<?php
$cache->clean();!!! note "Note"
The File handler also deletes cache entries whose key begins with a period, while the .htaccess, index.html, index.htm, index.php and web.config files are kept. Any other dot-leading file in the cache directory or its subdirectories (for example .gitignore, .env or .user.ini) is deleted as well.
- Returns: Information on the entire cache database
- Return type:
mixed
This method will return information on the entire cache.
Example:
<?php
var_dump($cache->getCacheInfo());!!! note "Note" The information returned and the structure of the data are dependent on which adapter is being used.
!!! note "Note"
The File handler also reports dot-leading files in the cache directory, including the .htaccess protection file.
-
Parameters
- $key
stringCache item name
- $key
-
Returns: Metadata for the cached item.
nullfor missing items, or an array with at least the "expire" key for absolute epoch expiry (nullfor never expires). -
Return type:
array|null
This method will return detailed information on a specific item in the cache.
Example:
<?php
var_dump($cache->getMetadata('my_cached_item'));!!! note "Note"
The information returned and the structure of the data are dependent on which adapter is being used. Some adapters (File, Memcached, Wincache) still return false for missing items.
-
Parameters
- $key
stringPotential cache key - $prefix
stringOptional prefix
- $key
-
Returns: The verified and prefixed key. If the key exceeds the driver's max key length it will be hashed.
-
Return type:
string
This method is used by handler methods to check that keys are valid. It will throw an InvalidArgumentException for non-strings, invalid characters, and empty lengths. The File handler additionally rejects /, \ and null bytes in the resulting file name, even when Config\Cache::$reservedCharacters is relaxed.
Example:
<?php
use CodeIgniter\Cache\Handlers\BaseHandler;
$prefixedKey = BaseHandler::validateKey($key, $prefix);APCu is an in-memory key-value store for PHP.
To use it, you need the APCu PHP extension.
This requires a cache directory to be writable by the application.
Use this with care, and make sure to benchmark your application, as a point can come where disk I/O will negate positive gains from caching.
Memcached servers can be specified in the cache configuration file. Available options are:
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Cache extends BaseConfig
{
// ...
public $memcached = [
'host' => '127.0.0.1',
'port' => 11211,
'weight' => 1,
'raw' => false,
];
// ...
}For more information on Memcached, please see https://www.php.net/memcached.
Under Windows, you can also utilize the WinCache driver.
For more information on WinCache, please see https://www.php.net/wincache.
Redis is an in-memory key-value store which can operate in LRU cache mode. To use it, you need the Redis server and phpredis PHP extension.
Config options to connect to the Redis server are stored in the cache configuration file. Available options are:
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Cache extends BaseConfig
{
// ...
public $redis = [
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'async' => false, // specific to Predis and ignored by the native Redis extension
'persistent' => false,
'timeout' => 0,
'database' => 0,
];
// ...
}For more information on Redis, please see https://redis.io.
Predis is a flexible and feature-complete PHP client library for the Redis key-value store. To use it, run the following from the command line inside your project root:
composer require predis/predisFor more information on Predis, please see https://github.com/nrk/predis.
This is a caching backend that will always 'miss.' It stores no data, but lets you keep your caching code in place in environments that don't support your chosen cache.