Redis Cache
The FilesCache.php
file is a concrete implementation of the abstract Cache
class in the PHPFast framework. It provides methods to store, retrieve, and manage cached data using the file system. Below is a detailed explanation of each method along with examples of how to use them.
connect()
connect()
Connect to the file-based cache system by setting up the cache directory.
<?php
protected function connect() {
$this->cacheDir = $this->config['cache_dir'] ?? sys_get_temp_dir();
if (!is_dir($this->cacheDir)) {
mkdir($this->cacheDir, 0777, true);
}
}
Sets the cache directory to the configured path or the system's temporary directory if not specified.
Creates the cache directory if it does not exist.
This method is called automatically when an instance of
RedisCache
is created.
set()
set()
function set($key, $value, $ttl = 3600)
Stores a value in the cache with a specified expiration time (Time-To-Live).
$key
– The key under which to store the value.$value
– The value to store.$ttl
– Time-to-live in seconds.$ttl
-true
if the value was successfully set,false
otherwise
Example:
<?php
$cache = new RedisCache();
$phpFast = 'Welcome to PHPFast Framework'
$cache->set('php_fast', $phpFast, 600); // Cache for 10 minutes
get()
get()
function get($key)
Retrieves a value from the cache using its unique key.
$key
– The key of the value to retrieve.return
– The value stored in the cache or null if not found
Example:
<?php
$phpFast = $cache->get('php_fast');
if ($phpFast !== null) {
echo "Data loaded from cache.";
} else {
echo "Data not found in cache.";
}
delete()
delete()
function delete($key)
Removes a specific cached value from the system.
$key
– The key of the value to delete.return
–true
if the value was successfully deleted,false
otherwise.
Example:
$cache->delete('php_fast');
has()
has()
function has($key)
Checks whether a specific key exists in the cache.
$key
– The key to check for existence.return
–true
if key exists,false
otherwise.
Example:
<?php
if ($cache->has('php_fast')) {
echo "Cache exists for php_fast.";
} else {
echo "No cache for php_fast.";
}
clear()
clear()
function clear()
Removes all cached entries, effectively resetting the cache storage.
return
–true
if the cache was successfully cleared,false
otherwise
Example:
$cache->clear();
Summary
The RedisCache.php
file extends the abstract Cache
class to provide Redis-based caching functionality. It includes methods to connect to the Redis server, store and retrieve cached data, delete cached data, check for the existence of cached data, and clear all cached data. This implementation allows developers to use Redis as a caching mechanism in their PHPFast applications.
Last updated
Was this helpful?