The CacheManager
class in JiFramework provides a flexible and unified interface for caching mechanisms within your application. It supports two types of cache drivers:
- File Cache: Stores cached data as files on the filesystem.
- SQLite Database Cache: Stores cached data in an SQLite database file.
By default, the framework uses the file cache driver, but you can switch to the SQLite database cache by updating the configuration. Both cache drivers implement the CacheInterface
, ensuring consistent method availability and behavior across different caching mechanisms.
By default, the framework uses the file cache driver, but you can configure the cache driver in your Config
class.
Setting the Cache Driver
In your Config
class, set the CACHE_DRIVER
constant to specify which cache driver to use.
namespace JIFramework\Config;
class Config {
// Available options: 'file', 'sqlite'
const CACHE_DRIVER = 'file'; // Default is 'file' if not set
}
Configuring File Cache (Default)
The file cache stores cached data in files within a specified directory. You can configure the cache directory:
class Config {
const CACHE_DRIVER = 'file';
const CACHE_PATH = self::STORAGE_PATH . 'Cache/FileCache/'; // Ensure this directory exists and is writable
}
- CACHE_PATH: Defines the directory where cache files are stored.
Note: Ensure that the cache directory exists and has appropriate read/write permissions.
Configuring SQLite Database Cache
If you choose to use the SQLite database cache, specify the path to the SQLite database file:
class Config {
const CACHE_DRIVER = 'sqlite';
const CACHE_DATABASE_PATH = self::STORAGE_PATH . 'Cache/DatabaseCache/ji_sqlite_cache.db';
}
- CACHE_DATABASE_PATH: Defines the path to the SQLite database file used for caching.
Note: Ensure that the directory for the database file exists and is writable.
Method: getInstance(string $cacheDriver = null): CacheInterface
Description: Retrieves the cache instance based on the configured cache driver. This method ensures that only one instance of the cache driver is used throughout your application (Singleton pattern).
Parameters:
- $cacheDriver (
string
, optional): The cache driver to use ('file'
or'sqlite'
). If not provided, it uses the value fromConfig::CACHE_DRIVER
.
Returns: An instance of CacheInterface
(either FileCache
or DatabaseCache
).
Usage:
use JIFramework\Core\App\App;
$app = new App();
// Get the cache instance based on configuration
$cache = $app->cache;
OR
use JIFramework\Core\Cache\CacheManager;
// Get the cache instance based on configuration
$cache = CacheManager::getInstance();
// Or specify the cache driver explicitly
$cache = CacheManager::getInstance('sqlite');
Explanation:
- The
getInstance
method checks the configured cache driver and initializes the appropriate cache instance. - If an unsupported cache driver is specified, it throws an exception.
Method: get(string $key)
Description: Retrieves an item from the cache by key.
Parameters:
- $key (
string
): The cache key.
Returns: The cached value, or null
if the item does not exist or is expired.
Usage:
// Get the cache instance based on configuration
$cache = CacheManager::getInstance();
// Retrieve a cached value
$value = $cache->get('user_123');
if ($value !== null) {
// Cache hit
echo 'Cached value: ' . $value;
} else {
// Cache miss
echo 'Cache miss. Fetching data...';
}
Explanation:
- The method generates the cache file path based on the key.
- It reads the cache file, unserializes the data, and checks for expiration.
- If the item is expired or does not exist, it returns
null
.
Method: set(string $key, $value, int $ttl = null): bool
Description: Stores an item in the cache.
Parameters:
- $key (
string
): The cache key. - $value (
mixed
): The data to cache. - $ttl (
int
, optional): Time-to-live in seconds. If not provided, the item does not expire.
Returns: bool
indicating success.
Usage:
// Cache data without expiration
$cache->set('user_123', $userData);
// Cache data with a TTL of 3600 seconds (1 hour)
$cache->set('user_123', $userData, 3600);
Explanation:
- The method generates the cache file path and calculates the expiration time.
- It serializes the value along with the expiration time and writes it to the cache file.
Method: delete(string $key): bool
Description: Deletes an item from the cache.
Parameters:
- $key (
string
): The cache key.
Returns: bool
indicating success.
Usage:
// Delete a cache item
$success = $cache->delete('user_123');
if ($success) {
echo 'Cache item deleted.';
} else {
echo 'Cache item not found.';
}
Explanation:
- The method checks if the cache file exists and attempts to delete it.
- Returns
true
if the file was deleted,false
otherwise.
Method: has(string $key): bool
Description: Checks if a cache item exists and is still valid.
Parameters:
- $key (
string
): The cache key.
Returns: bool
Usage:
// Check if a cache item exists
if ($cache->has('user_123')) {
echo 'Cache item exists.';
} else {
echo 'Cache item does not exist or is expired.';
}
Explanation:
- Similar to
get
, but returns a boolean instead of the value. - Useful for checking the existence of a cache item without retrieving it.
Method: increment(string $key, int $value = 1): int|bool
Description: Increments the value of a numeric cache item.
Parameters:
- $key (
string
): The cache key. - $value (
int
, optional): The value to increment by. Defaults to1
.
Returns: The new value after incrementing, or false
on failure.
Usage:
// Increment a counter
$newValue = $fileCache->increment('page_views');
if ($newValue !== false) {
echo 'New page views count: ' . $newValue;
} else {
echo 'Failed to increment.';
}
Explanation:
- Retrieves the current value, ensures it's numeric, increments it, and saves it back.
- Returns the new value or
false
if the operation fails.
Method: decrement(string $key, int $value = 1): int|bool
Description:
Decrements the value of a numeric cache item.
Parameters:
- $key (
string
): The cache key. - $value (
int
, optional): The value to decrement by. Defaults to1
.
Returns: The new value after decrementing, or false
on failure.
Usage:
// Decrement a counter
$newValue = $cache->decrement('available_slots', 2);
if ($newValue !== false) {
echo 'Available slots: ' . $newValue;
} else {
echo 'Failed to decrement.';
}
Explanation:
- Similar to
increment
, but decreases the value. - Useful for tracking counts that decrease over time.
Method: gc(): void
Description: Performs garbage collection to remove expired cache items.
Parameters: None
Returns: void
Usage:
// Perform garbage collection
$cache->gc();
echo 'Expired cache items removed.';
Explanation:
- Iterates over cache files and deletes those that have expired.
- Helps prevent accumulation of outdated cache files.