Skip to content

MCache

Overview

MCache is a simple and lightweight PHP class that allows caching variables or objects in files. It is particularly useful for storing expensive computation results or frequently used data that doesn't change often.

Features

  • Storage of any serializable variable (arrays, objects, etc.)
  • Cache data expiration management
  • Simple interface with only three main methods
  • Global cache disabling if necessary

Basic Usage

Initialization

use mlib\utils\cache\MCache;

// Create a MCache instance with a cache directory
$cache = new MCache('/path/to/cache/');

Store a value in cache

// Store a simple value
$cache->set('my_key', 'my_value');

// Store an array
$data = ['name' => 'Dupont', 'firstname' => 'John'];
$cache->set('user_123', $data);

// Store an object
$object = new MyClass();
$cache->set('my_object', $object);

Retrieve a value from cache

// Retrieve a value without expiration
$value = $cache->get('my_key');

// Retrieve a value with 1 hour expiration (3600 seconds)
$data = $cache->get('user_123', 3600);

// Check if cache exists
if ($data === false) {
    // Cache expired or doesn't exist
    $data = // ... expensive computation or retrieval ...
    $cache->set('user_123', $data);
}

Delete a cache entry

$cache->delete('my_key');

Advanced Management

Disable cache globally

It is possible to completely disable cache for all MCache instances:

// Disable cache globally
MCache::disable();

// All subsequent calls to set() will be ignored
// All calls to get() will return false
$cache = new MCache('/path/to/cache/');
$cache->set('test', 'value'); // Will do nothing
$value = $cache->get('test'); // Will return false

This can be useful for temporarily disabling cache during development phases, or during maintenance.

Cache file management

Cache files are stored in the directory specified when instantiating the class. Each entry is stored in a separate file with the .cache extension.

Example of file structure:

/cache/
    user_123.cache
    my_object.cache
    my_key.cache

Best Practices

  1. Key choice: Use descriptive and unique keys to avoid collisions.

  2. Error handling: Always check the return value of get() which can be false if the cache doesn't exist or has expired.

  3. Expiration: Use appropriate expiration durations based on the update frequency of your data.

  4. Cleanup: Set up a mechanism for cleaning old cache files if necessary.

  5. Security: Ensure the cache directory is not directly accessible from the web.

Complete Example

use mlib\utils\cache\MCache;

class MyService {
    private $cache;

    public function __construct() {
        $this->cache = new MCache(__DIR__ . '/../cache/');
    }

    public function getUserData($userId) {
        $cacheKey = 'user_' . $userId;

        // Try to get data from cache (valid for 1h)
        $data = $this->cache->get($cacheKey, 3600);

        if ($data === false) {
            // Data not in cache or expired
            $data = $this->retrieveDataFromDatabase($userId);

            // Cache for next time
            $this->cache->set($cacheKey, $data);
        }

        return $data;
    }

    public function updateUserData($userId, $newData) {
        // Update database
        $this->updateDatabase($userId, $newData);

        // Invalidate cache
        $cacheKey = 'user_' . $userId;
        $this->cache->delete($cacheKey);
    }

    private function retrieveDataFromDatabase($userId) {
        // Simulation of expensive database call
        sleep(2);
        return [
            'id' => $userId,
            'name' => 'Dupont',
            'firstname' => 'John',
            'email' => 'john.dupont@example.com',
            'last_login' => date('Y-m-d H:i:s')
        ];
    }

    private function updateDatabase($userId, $data) {
        // Database update logic
        // ...
    }
}

// Usage
$service = new MyService();

// First read - slow (caches)
$data1 = $service->getUserData(123);

// Second read - fast (from cache)
$data2 = $service->getUserData(123);

// Data update
$service->updateUserData(123, ['email' => 'new.email@example.com']);

// Next read - slow because cache was invalidated
$data3 = $service->getUserData(123);