Skip to main content

Cache

Description: This example demonstrates the usage of the Cache class, defined under the PINGOJS namespace. The Cache class provides methods for managing cache data, including adding, retrieving, and removing cached content, as well as handling long-term cache storage.


Namespace

use PINGOJS\Cache;

Example Usage

$cache = new Cache('/path/to/cache/');

Methods

add($name, $content, $exe)

Creates a new cache file with the specified name, content, and file extension.

Parameters:

  • $name: Name of the file (without extension).
  • $content: Data to be written to the file.
  • $exe: File extension.

Example Usage

$cache->add('example', 'Sample Content', 'txt');

get($name, $exe)

Reads the content of a specified cache file.

Parameters:

  • $name: Name of the file (without extension).
  • $exe: File extension.

Example Usage

$content = $cache->get('example', 'txt');
echo $content;

cacheDataForever($key, $data)

Stores serialized data with a unique key for long-term caching.

Parameters:

  • $key: A unique identifier for the cached data.
  • $data: Data to be serialized and stored.

Example Usage

$cache->cacheDataForever('user_profile', ['name' => 'John', 'age' => 30]);

getCacheForever($key)

Retrieves long-term cached data using a unique key.

Parameters:

  • $key: The unique identifier for the cached data.

Example Usage

$data = $cache->getCacheForever('user_profile');
print_r($data);

removeCacheForever($key)

Deletes long-term cached data associated with a unique key.

Parameters:

  • $key: The unique identifier for the cached data.

Example Usage

$cache->removeCacheForever('user_profile');

Practical Example

Here’s how you can use the Cache class to manage cache data in your application:

$cache = new Cache('/tmp/cache/');

// Add a cache file
$cache->add('settings', json_encode(['theme' => 'dark']), 'json');

// Retrieve the cache file content
$settings = $cache->get('settings', 'json');
echo $settings;

// Store long-term cache data
$cache->cacheDataForever('session_data', ['id' => 123, 'token' => 'abc123']);

// Retrieve long-term cache data
$session = $cache->getCacheForever('session_data');
print_r($session);

// Remove long-term cache data
$cache->removeCacheForever('session_data');

Conclusion

The Cache class simplifies file-based caching operations, ensuring flexibility and efficiency. Use this class to enhance your application’s performance by reducing redundant data processing.