Kotchasan Framework Documentation

Kotchasan Framework Documentation

Kotchasan\Cache\QueryCache

EN 05 Feb 2026 07:40

Kotchasan\Cache\QueryCache

QueryCache is a specialized cache wrapper for database query caching. It automatically generates cache keys from SQL queries and parameters.

Table of Contents

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

Overview

QueryCache features:

  • Automatic Key Generation: Creates cache key from SQL + parameters
  • Query Builder Integration: Works directly with QueryBuilder
  • Enable/Disable: Toggle caching at runtime
  • Statistics: Tracks hits, misses, writes
  • Table Invalidation: Clear cache when table is modified

When to use:

  • Cache database query results
  • Complex, time-consuming queries
  • Data that doesn't change frequently

Installation and Usage

Requirements

  • PHP 7.4 or higher
  • Kotchasan Framework
  • Cache implementation (FileCache, RedisCache, or MemoryCache)

Basic Usage

use Kotchasan\Cache\QueryCache;
use Kotchasan\Cache\FileCache;
use Kotchasan\Database;

// Create underlying cache
$fileCache = new FileCache(['path' => ROOT_PATH . 'datas/cache/']);

// Create QueryCache
$queryCache = new QueryCache($fileCache, 3600);

// Use with Database
Database::setCache($fileCache, 3600);

// Queries are cached automatically
$db = Database::create();
$users = $db->select('*')
    ->from('users')
    ->where('status', '=', 'active')
    ->cache(true)  // Enable cache for this query
    ->execute();

Main Methods

__construct()

Signature:

public function __construct(CacheInterface $cache, int $defaultTtl = 3600)

get() / set()

Get/set cached query results.

public function get(QueryBuilderInterface $query)
public function set(QueryBuilderInterface $query, $result, ?int $ttl = null): bool

getByKey() / setByKey()

Use raw SQL instead of QueryBuilder.

public function getByKey(string $sql, array $params = [])
public function setByKey(string $sql, array $params, $result, ?int $ttl = null): bool

invalidate() / invalidateTable()

Clear cache for query or table.

public function invalidate(QueryBuilderInterface $query): bool
public function invalidateTable(string $table): bool

enable() / disable() / isEnabled()

Toggle caching.

public function enable(): self
public function disable(): self
public function isEnabled(): bool

getStats()

Get cache statistics.

Returns:

[
    'hits' => 500,
    'misses' => 100,
    'writes' => 300,
    'enabled' => true,
    'default_ttl' => 3600,
    'backend' => 'Kotchasan\\Cache\\FileCache'
]

Usage Examples

1. Basic Query Caching

use Kotchasan\Cache\QueryCache;
use Kotchasan\Cache\FileCache;
use Kotchasan\Database;

$fileCache = new FileCache(['path' => ROOT_PATH . 'datas/cache/']);
$queryCache = new QueryCache($fileCache, 3600);
$db = Database::create();

$query = $db->select('*')
    ->from('products')
    ->where('category', '=', 'electronics');

// Check cache first
$products = $queryCache->get($query);
if ($products === null) {
    $products = $query->execute();
    $queryCache->set($query, $products, 600);
}

2. Invalidate Cache on Data Change

class ProductRepository
{
    private QueryCache $queryCache;
    private Database $db;

    public function update(int $id, array $data): bool
    {
        $result = $this->db->update('products')
            ->set($data)
            ->where('id', '=', $id)
            ->execute();

        if ($result) {
            // Clear related cache
            $this->queryCache->invalidateTable('products');
        }

        return $result;
    }
}

3. Using with Kotchasan\Database

use Kotchasan\Database;

Database::configureCache([
    'driver' => 'file',
    'path' => ROOT_PATH . 'datas/cache/'
], 3600);

$db = Database::create();

$users = $db->select('*')
    ->from('users')
    ->where('status', '=', 'active')
    ->cache(true, 600)  // Cache for 10 minutes
    ->execute();

Best Practices

1. Use Appropriate TTL

// Static data - long TTL
$queryCache->set($categoryQuery, $categories, 86400); // 24 hours

// Frequently changing data - short TTL
$queryCache->set($orderQuery, $orders, 60); // 1 minute

2. Invalidate Cache Correctly

function updateUser($id, $data)
{
    $db->update('users')->set($data)->where('id', '=', $id)->execute();
    $queryCache->invalidateTable('users');
}

Warnings

⚠️ Warning:

  • Don't cache frequently changing queries
  • Remember to invalidate cache on data changes
  • Watch for stale data