Caching Engine
Relevant source files
The following files were used as context for generating this wiki page:
The CodeIgniter 4 Caching Engine provides a flexible and unified API for various caching backends. Its primary purpose is to improve application performance by storing the results of expensive operations and retrieving them from the cache on subsequent requests, thus avoiding repeated computation. The system is designed to be driver-based, allowing developers to switch between different caching solutions with minimal configuration changes.
The engine is accessed through a service, which uses a factory to instantiate the appropriate cache handler based on the application's configuration. This architecture supports multiple handlers like File, Redis, Memcached, and a Dummy handler for development or testing environments where caching is not desired.
Sources: user_guide_src/source/libraries/caching.rst:3-11
Configuration
The Caching Engine's behavior is primarily controlled by the app/Config/Cache.php file. This configuration class allows you to specify the default handler, a backup handler, and settings specific to each supported driver.
Sources: app/Config/Cache.php
Main Configuration Options
| Property | Type | Default | Description |
|---|---|---|---|
$handler | string | file | The primary cache handler to use. |
$backupHandler | string | dummy | The handler to use if the primary handler is unavailable. |
$prefix | string | '' | A prefix to be prepended to all cache keys, preventing key collisions. |
$ttl | int | 60 | The default time-to-live for a cache item in seconds. |
$path | string | WRITEPATH . 'cache/' | The full path for the FileHandler to store cache files. |
Sources: app/Config/Cache.php:20-44
Handler-Specific Configurations
The configuration file also contains properties for specific handlers, such as connection details for Redis or Memcached.
// app/Config/Cache.php
// ...
public $file = [
'path' => null,
'prefix' => null,
];
public $memcached = [
'host' => '127.0.0.1',
'port' => 11211,
'weight' => 1,
'raw' => false,
];
public $redis = [
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'timeout' => 0,
'database' => 0,
];
// ...
Sources: app/Config/Cache.php:46-77
Core Architecture
The Caching Engine is built around a factory pattern, a common interface, and multiple handler implementations. This design promotes loose coupling and makes it easy to extend the system with custom cache handlers.
Component Interaction
The following diagram illustrates how a user's code interacts with the caching service to retrieve a handler instance.
This diagram shows the flow of getting a cache handler instance, starting from the application code, through the service, to the factory which instantiates the configured handler.
Sources: system/Cache/CacheFactory.php:26-51, app/Config/Cache.php
Class Structure
The core components include the CacheFactory, the CacheInterface which defines the contract for all handlers, and the concrete handler implementations.
This diagram shows that CacheFactory produces an object that implements CacheInterface. FileHandler, RedisHandler, and DummyHandler are all concrete implementations of this interface.
Sources: system/Cache/CacheFactory.php, system/Cache/CacheInterface.php, system/Cache/Handlers/FileHandler.php, system/Cache/Handlers/RedisHandler.php, system/Cache/Handlers/DummyHandler.php
Basic Usage
To use the caching library, you first need to get an instance of it through the Services class. Once you have the cache object, you can use its methods to store and retrieve data.
$cache = \Config\Services::cache();
if (! $foo = $cache->get('foo')) {
// ... saving item to cache
$cache->save('foo', $foo, 300);
}
Sources: user_guide_src/source/libraries/caching.rst:29-43
Get and Save Sequence
The following diagram shows the sequence of events for a typical cache-get operation, including a cache miss and subsequent save.
This sequence illustrates the "cache-aside" pattern where the application code is responsible for checking the cache, generating data on a miss, and saving it back to the cache.
Sources: user_guide_src/source/libraries/caching.rst:29-43, system/Cache/CacheInterface.php:33-51
Supported Handlers
CodeIgniter 4 ships with several built-in handlers.
| Handler | Description |
|---|---|
FileHandler | Caches data as serialized files on the local filesystem. Simple and requires no external dependencies. |
RedisHandler | Uses a Redis server for caching. Offers high performance and advanced features. Requires the php-redis extension. |
MemcachedHandler | Uses a Memcached server for caching. A distributed, in-memory cache system. Requires the php-memcached extension. |
DummyHandler | A "black hole" cache that doesn't store any data. Useful for development or disabling cache without code changes. |
Sources: user_guide_src/source/libraries/caching.rst:133-156, app/Config/Cache.php:23
FileHandler
The FileHandler is the default handler. It serializes the cached data and stores it in files located in the directory specified by $path in the configuration. The cache key is used to generate the filename, typically after being hashed.
The handler ensures the cache directory exists and is writable upon initialization. Metadata, including the expiration time (ttl), is stored within the same file as the cached data.
Sources: system/Cache/Handlers/FileHandler.php:35-47, 107-111
RedisHandler
The RedisHandler connects to a Redis server using the credentials provided in app/Config/Cache.php. It leverages the speed of Redis as an in-memory data store. It requires the php-redis PECL extension to be installed and enabled.
Sources: system/Cache/Handlers/RedisHandler.php:49-62, user_guide_src/source/libraries/caching.rst:147-148
DummyHandler
The DummyHandler provides a no-op implementation of the CacheInterface. All methods return predictable, non-operative values (e.g., get() always returns null, save() always returns true). This is useful for disabling caching in certain environments without needing to add conditional logic throughout the application.
Sources: system/Cache/Handlers/DummyHandler.php:22-83
Core Functionality
All cache handlers must implement the CacheInterface, which guarantees a consistent API for interacting with the cache regardless of the backend used.
| Method | Description |
|---|---|
get(string $key) | Retrieves an item from the cache by its key. Returns null if the item does not exist. |
save(string $key, $value, int $ttl = 60) | Persists data in the cache for a specified number of seconds ($ttl). |
delete(string $key) | Removes a single item from the cache. |
increment(string $key, int $offset = 1) | Increments a numeric item's value. |
decrement(string $key, int $offset = 1) | Decrements a numeric item's value. |
clean() | Deletes all items from the cache. |
getCacheInfo() | Returns detailed information about the cache server/backend. |
getMetaData(string $key) | Returns metadata for a specific cache item, like expire time and name. |
Sources: system/Cache/CacheInterface.php:33-98
Conclusion
The CodeIgniter 4 Caching Engine is a powerful yet simple feature for improving application performance. Its driver-based architecture, centered around the CacheInterface and CacheFactory, provides a consistent API while allowing developers to choose the backend that best fits their needs, from a simple file-based cache to high-performance in-memory stores like Redis. Configuration is centralized and straightforward, making it easy to manage cache behavior across different environments.
Sources: user_guide_src/source/libraries/caching.rst, system/Cache/CacheFactory.php