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 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()

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()

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()

function delete($key)

Removes a specific cached value from the system.

  • $key – The key of the value to delete.

  • returntrue if the value was successfully deleted, false otherwise.

Example:

$cache->delete('php_fast');

has()

function has($key)

Checks whether a specific key exists in the cache.

  • $key – The key to check for existence.

  • returntrue 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()

function clear()

Removes all cached entries, effectively resetting the cache storage.

  • returntrue if the cache was successfully cleared, false otherwise

Example:

$cache->clear();

Last updated

Was this helpful?