Kotchasan Framework Documentation

Kotchasan Framework Documentation

Kotchasan\Cache\MemoryCache

EN 05 Feb 2026 07:40

Kotchasan\Cache\MemoryCache

MemoryCache is a cache system that stores data in memory (PHP array). It's ideal for caching data within a single request. Data is lost when the script ends.

Table of Contents

  1. Overview
  2. Installation and Usage
  3. Main Methods
  4. Usage Examples
  5. Best Practices

Overview

MemoryCache features:

  • Fast Access: Fastest data access (in memory)
  • Request Scope: Data exists only in current request
  • LRU Eviction: Uses Least Recently Used algorithm for eviction
  • Statistics: Tracks hits, misses, writes stats

When to use:

  • Cache results during processing within the same request
  • Avoid repeated calculations
  • No need for persistence across requests

Installation and Usage

Requirements

  • PHP 7.4 or higher
  • Kotchasan Framework

Basic Usage

use Kotchasan\Cache\MemoryCache;

// Create instance with configuration
$cache = new MemoryCache(
    3600,  // Default TTL 1 hour
    1000   // Maximum 1000 items
);

// Save to cache
$cache->set('user_data', ['name' => 'John', 'email' => 'john@example.com']);

// Retrieve from cache
$userData = $cache->get('user_data');
// Result: ['name' => 'John', 'email' => 'john@example.com']

Main Methods

__construct()

Create a MemoryCache instance.

Signature:

public function __construct(int $defaultTtl = 3600, int $maxItems = 1000)

Parameters:

  • $defaultTtl (int) - Default TTL in seconds - default: 3600
  • $maxItems (int) - Maximum number of items to store - default: 1000

get()

Retrieve value from cache.

Signature:

public function get(string $key, $default = null)

Parameters:

  • $key (string) - Cache item key
  • $default (mixed) - Default value if not found

Returns: Cached value or default if not found or expired.

set()

Store value in cache.

Signature:

public function set(string $key, $value, ?int $ttl = null): bool

Parameters:

  • $key (string) - Cache item key
  • $value (mixed) - Value to store
  • $ttl (int|null) - TTL in seconds (null = use default)

Returns: Always true.

delete()

Delete a cache item.

Signature:

public function delete(string $key): bool

clear()

Clear all cache items.

Signature:

public function clear(): bool

has()

Check if a key exists in cache.

Signature:

public function has(string $key): bool

getMultiple() / setMultiple() / deleteMultiple()

Manage multiple keys at once.

Signatures:

public function getMultiple(iterable $keys, $default = null): iterable
public function setMultiple(iterable $values, ?int $ttl = null): bool
public function deleteMultiple(iterable $keys): bool

getStats()

Get cache usage statistics.

Signature:

public function getStats(): array

Returns:

[
    'hits' => 150,      // Cache hit count
    'misses' => 20,     // Cache miss count
    'writes' => 100,    // Write count
    'deletes' => 5,     // Delete count
    'count' => 75,      // Current item count
    'size' => 102400,   // Approximate size (bytes)
    'max_items' => 1000 // Maximum items allowed
]

Usage Examples

1. Cache Computation Results

use Kotchasan\Cache\MemoryCache;

$cache = new MemoryCache();

function calculateExpensiveResult($id, MemoryCache $cache)
{
    $key = "calculation_{$id}";

    // Check cache first
    $result = $cache->get($key);
    if ($result !== null) {
        return $result; // Return from cache
    }

    // Compute (expensive operation)
    $result = heavyComputation($id);

    // Store in cache
    $cache->set($key, $result, 60);

    return $result;
}

// Call multiple times - 2nd+ calls use cache
$result1 = calculateExpensiveResult(123, $cache);
$result2 = calculateExpensiveResult(123, $cache); // From cache!

2. Cache Configuration During Request

use Kotchasan\Cache\MemoryCache;

class ConfigService
{
    private MemoryCache $cache;

    public function __construct()
    {
        // Store up to 100 config items
        $this->cache = new MemoryCache(0, 100);
    }

    public function get(string $key, $default = null)
    {
        // Get from cache first
        if ($this->cache->has($key)) {
            return $this->cache->get($key);
        }

        // Load from database
        $value = $this->loadFromDatabase($key) ?? $default;

        // Cache it (TTL = 0 = no expiry in this request)
        $this->cache->set($key, $value, 0);

        return $value;
    }

    private function loadFromDatabase(string $key)
    {
        // ... load from DB
        return null;
    }
}

3. Working with Multiple Keys

use Kotchasan\Cache\MemoryCache;

$cache = new MemoryCache();

// Store multiple values at once
$cache->setMultiple([
    'user_1' => ['name' => 'John'],
    'user_2' => ['name' => 'Jane'],
    'user_3' => ['name' => 'Bob']
], 3600);

// Retrieve multiple values at once
$users = $cache->getMultiple(['user_1', 'user_2', 'user_4'], null);
// Result: ['user_1' => [...], 'user_2' => [...], 'user_4' => null]

// Delete multiple values at once
$cache->deleteMultiple(['user_1', 'user_2']);

4. Track Cache Statistics

use Kotchasan\Cache\MemoryCache;

$cache = new MemoryCache(3600, 500);

// Use cache...
$cache->set('key1', 'value1');
$cache->get('key1');
$cache->get('key2'); // miss

// View statistics
$stats = $cache->getStats();

echo "Cache Hits: {$stats['hits']}\n";
echo "Cache Misses: {$stats['misses']}\n";
echo "Hit Ratio: " . ($stats['hits'] / ($stats['hits'] + $stats['misses']) * 100) . "%\n";
echo "Items in Cache: {$stats['count']}\n";

Best Practices

1. Set Appropriate MaxItems

// For requests with lots of data
$cache = new MemoryCache(3600, 5000);

// For typical requests
$cache = new MemoryCache(3600, 1000);

// For memory-limited environments
$cache = new MemoryCache(3600, 100);

2. Use TTL = 0 for Session Data

// Data needed throughout the request
$cache->set('current_user', $user, 0);

// Data that might change
$cache->set('product_list', $products, 60);

3. Check Statistics for Tuning

$stats = $cache->getStats();

// If hit ratio is low, might need to increase maxItems
if ($stats['hits'] / ($stats['hits'] + $stats['misses']) < 0.5) {
    // Consider increasing cache size
}

Warnings

⚠️ Warning: MemoryCache is NOT suitable for:

  • Sharing data between requests
  • Persisting data across scripts
  • Large amounts of data (memory limited)

💡 Tip: Use with RedisCache or FileCache for persistent caching