Kotchasan Framework Documentation

Kotchasan Framework Documentation

Kotchasan\Cache\MemoryCache

TH 05 Feb 2026 07:40

Kotchasan\Cache\MemoryCache

MemoryCache เป็นระบบ Cache ที่เก็บข้อมูลในหน่วยความจำ (PHP array) เหมาะสำหรับการ cache ข้อมูลภายใน request เดียวกัน ข้อมูลจะหายไปเมื่อ script ทำงานเสร็จ

สารบัญ

  1. ภาพรวม
  2. การติดตั้งและใช้งาน
  3. เมธอดหลัก
  4. ตัวอย่างการใช้งาน
  5. Best Practices

ภาพรวม

MemoryCache มีคุณสมบัติดังนี้:

  • Fast Access: เข้าถึงข้อมูลได้เร็วที่สุด (อยู่ในหน่วยความจำ)
  • Request Scope: ข้อมูลมีอยู่เฉพาะใน request ปัจจุบัน
  • LRU Eviction: ใช้ Least Recently Used algorithm ในการลบข้อมูลเก่า
  • Statistics: ติดตามสถิติ hits, misses, writes

เมื่อไหร่ควรใช้:

  • ต้องการ cache ผลลัพธ์ระหว่างการประมวลผลใน request เดียวกัน
  • หลีกเลี่ยงการคำนวณซ้ำหลายครั้ง
  • ไม่ต้องการ persistence ข้าม requests

การติดตั้งและใช้งาน

ความต้องการ

  • PHP 7.4 หรือสูงกว่า
  • Kotchasan Framework

การใช้งานพื้นฐาน

use Kotchasan\Cache\MemoryCache;

// สร้าง instance พร้อมกำหนดค่า
$cache = new MemoryCache(
    3600,  // Default TTL 1 ชั่วโมง
    1000   // เก็บได้สูงสุด 1000 items
);

// บันทึก cache
$cache->set('user_data', ['name' => 'John', 'email' => 'john@example.com']);

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

เมธอดหลัก

__construct()

สร้าง instance ของ MemoryCache

Signature:

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

Parameters:

  • $defaultTtl (int) - TTL เริ่มต้น (วินาที) - default: 3600
  • $maxItems (int) - จำนวน items สูงสุดที่เก็บได้ - default: 1000

get()

ดึงค่าจาก cache

Signature:

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

Parameters:

  • $key (string) - Key ของ cache item
  • $default (mixed) - ค่า default ถ้าไม่พบ

Returns: ค่าที่ cache ไว้ หรือ default ถ้าไม่พบหรือหมดอายุ

set()

บันทึกค่าลง cache

Signature:

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

Parameters:

  • $key (string) - Key ของ cache item
  • $value (mixed) - ค่าที่จะบันทึก
  • $ttl (int|null) - TTL เป็นวินาที (null = ใช้ค่า default)

Returns: true เสมอ

delete()

ลบ cache item

Signature:

public function delete(string $key): bool

clear()

ล้าง cache ทั้งหมด

Signature:

public function clear(): bool

has()

ตรวจสอบว่ามี key อยู่ใน cache หรือไม่

Signature:

public function has(string $key): bool

getMultiple() / setMultiple() / deleteMultiple()

จัดการหลาย keys พร้อมกัน

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

ดึงสถิติการใช้งาน cache

Signature:

public function getStats(): array

Returns:

[
    'hits' => 150,      // จำนวนครั้งที่เจอ cache
    'misses' => 20,     // จำนวนครั้งที่ไม่พบ
    'writes' => 100,    // จำนวนครั้งที่เขียน
    'deletes' => 5,     // จำนวนครั้งที่ลบ
    'count' => 75,      // จำนวน items ปัจจุบัน
    'size' => 102400,   // ขนาดโดยประมาณ (bytes)
    'max_items' => 1000 // จำนวนสูงสุดที่เก็บได้
]

ตัวอย่างการใช้งาน

1. Cache ผลลัพธ์การคำนวณ

use Kotchasan\Cache\MemoryCache;

$cache = new MemoryCache();

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

    // ตรวจสอบ cache ก่อน
    $result = $cache->get($key);
    if ($result !== null) {
        return $result; // คืนค่าจาก cache
    }

    // คำนวณ (สิ่งที่ใช้เวลา)
    $result = heavyComputation($id);

    // บันทึก cache
    $cache->set($key, $result, 60);

    return $result;
}

// เรียกใช้หลายครั้ง - ครั้งที่ 2+ จะได้จาก cache
$result1 = calculateExpensiveResult(123, $cache);
$result2 = calculateExpensiveResult(123, $cache); // จาก cache!

2. Cache Configuration ระหว่าง Request

use Kotchasan\Cache\MemoryCache;

class ConfigService
{
    private MemoryCache $cache;

    public function __construct()
    {
        // เก็บได้ 100 config items
        $this->cache = new MemoryCache(0, 100);
    }

    public function get(string $key, $default = null)
    {
        // ดึงจาก cache ก่อน
        if ($this->cache->has($key)) {
            return $this->cache->get($key);
        }

        // ดึงจาก database
        $value = $this->loadFromDatabase($key) ?? $default;

        // Cache ไว้ (TTL = 0 = ไม่หมดอายุใน request นี้)
        $this->cache->set($key, $value, 0);

        return $value;
    }

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

3. การใช้งานกับ Multiple Keys

use Kotchasan\Cache\MemoryCache;

$cache = new MemoryCache();

// บันทึกหลายค่าพร้อมกัน
$cache->setMultiple([
    'user_1' => ['name' => 'John'],
    'user_2' => ['name' => 'Jane'],
    'user_3' => ['name' => 'Bob']
], 3600);

// ดึงหลายค่าพร้อมกัน
$users = $cache->getMultiple(['user_1', 'user_2', 'user_4'], null);
// Result: ['user_1' => [...], 'user_2' => [...], 'user_4' => null]

// ลบหลายค่าพร้อมกัน
$cache->deleteMultiple(['user_1', 'user_2']);

4. ติดตามสถิติ Cache

use Kotchasan\Cache\MemoryCache;

$cache = new MemoryCache(3600, 500);

// ใช้งาน cache...
$cache->set('key1', 'value1');
$cache->get('key1');
$cache->get('key2'); // miss

// ดู 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. กำหนด MaxItems ให้เหมาะสม

// สำหรับ request ที่มี data จำนวนมาก
$cache = new MemoryCache(3600, 5000);

// สำหรับ request ทั่วไป
$cache = new MemoryCache(3600, 1000);

// สำหรับ memory-limited environments
$cache = new MemoryCache(3600, 100);

2. ใช้ TTL = 0 สำหรับ Session Data

// ข้อมูลที่ต้องการตลอด request
$cache->set('current_user', $user, 0);

// ข้อมูลที่อาจเปลี่ยนแปลง
$cache->set('product_list', $products, 60);

3. ตรวจสอบสถิติเพื่อปรับแต่ง

$stats = $cache->getStats();

// ถ้า hit ratio ต่ำ อาจต้องเพิ่ม maxItems
if ($stats['hits'] / ($stats['hits'] + $stats['misses']) < 0.5) {
    // พิจารณาเพิ่ม cache size
}

ข้อควรระวัง

⚠️ Warning: MemoryCache ไม่เหมาะสำหรับ:

  • การ share ข้อมูลระหว่าง requests
  • การ persist ข้อมูลข้าม script
  • ข้อมูลขนาดใหญ่ (หน่วยความจำมีจำกัด)

💡 Tip: ใช้ร่วมกับ RedisCache หรือ FileCache สำหรับ persistent caching

คลาสที่เกี่ยวข้อง