Files Cache

The FilesCache.php file is a concrete implementation of the abstract Cache class. It provides methods to store, retrieve, and manage cached data using the file system. Below is an explanation of the code in FilesCache.php.

It provides methods to store, retrieve, and manage cached data using the file system. Below is an explanation of each method in FilesCache.php along with examples:

set()

function set($key, $value, $ttl = 3600)

Stores a value in the cache with a specified time-to-live (TTL). The value is serialized and saved in a file identified by the MD5 hash of the key.

  • $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 FilesCache()
$cache->set('php_fast', ['name' => 'PHPFast Framework', 'version' => '1.0'], 600);

get()

function get($key)

Retrieves a cached value using its key. If the key exists, the stored data is unserialized and returned; otherwise, null is returned.

  • $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 cached value based on the provided key. If the key exists, the corresponding data is deleted from the cache.

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

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

Example:

<?php
$cache->delete('php_fast');

has()

function has($key)

Checks whether a specific key exists in the cache. Returns true if the key is found, otherwise returns false.

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

Clears all cached data, effectively resetting the cache system by removing all stored keys and their values.

  • returntrue if the cache was successfully cleared, false otherwise

Example:

<?php
$cache->clear();

Last updated

Was this helpful?