Kotchasan Framework Documentation
Kotchasan\Cache\RedisCache
Kotchasan\Cache\RedisCache
RedisCache is a cache system that stores data in a Redis server, enabling data sharing across requests and multiple processes.
Table of Contents
Overview
RedisCache features:
- Persistent: Data persists even after script ends
- Distributed: Share cache between multiple servers
- Fast: Redis is a fast in-memory database
- Feature Rich: Supports TTL, prefix, and statistics
Requirements:
- Redis server
- phpredis extension
When to use:
- Need cache that persists across requests
- Share cache between multiple application servers
- Large amounts of data to cache
Installation and Usage
System Requirements
- PHP 7.4 or higher
- Redis server (4.0+)
- phpredis extension
Installing phpredis
# Ubuntu/Debian
sudo apt-get install php-redis
# CentOS/RHEL
sudo yum install php-redis
# Or via PECL
pecl install redisBasic Usage
use Kotchasan\Cache\RedisCache;
// Create instance and connect to Redis
$cache = new RedisCache(
'127.0.0.1', // host
6379, // port
null, // password (null = none)
0, // database number
'myapp_', // key prefix
3600 // default TTL
);
// Store in cache
$cache->set('user:1', ['name' => 'John', 'email' => 'john@example.com']);
// Retrieve from cache
$userData = $cache->get('user:1');
// Result: ['name' => 'John', 'email' => 'john@example.com']Main Methods
__construct()
Create instance and connect to Redis.
Signature:
public function __construct(
string $host = '127.0.0.1',
int $port = 6379,
?string $password = null,
int $database = 0,
string $prefix = 'kotchasan_',
int $defaultTtl = 3600
)Parameters:
$host- Redis server host$port- Redis server port$password- Password for authentication (optional)$database- Database number (0-15)$prefix- Prefix for all keys$defaultTtl- Default TTL in seconds
connect()
Connect to Redis server.
Signature:
public function connect(): boolReturns: true if connection successful.
get() / set() / delete() / has() / clear()
Standard cache operations (same as other cache implementations).
isAvailable()
Check if Redis is available.
Signature:
public function isAvailable(): boolgetStats()
Get usage statistics.
Returns:
[
'hits' => 1500,
'misses' => 200,
'writes' => 1000,
'connected' => true,
'server_info' => [...] // Info from Redis INFO command
]getRedis()
Get Redis connection for direct use.
Signature:
public function getRedis(): ?\RedisUsage Examples
1. Session Store
use Kotchasan\Cache\RedisCache;
class SessionStore
{
private RedisCache $cache;
public function __construct()
{
$this->cache = new RedisCache(
'localhost', 6379, null, 0,
'session_',
1800 // 30 minutes
);
}
public function save(string $sessionId, array $data): bool
{
return $this->cache->set($sessionId, $data);
}
public function load(string $sessionId): ?array
{
return $this->cache->get($sessionId);
}
public function destroy(string $sessionId): bool
{
return $this->cache->delete($sessionId);
}
}2. Rate Limiting
use Kotchasan\Cache\RedisCache;
class RateLimiter
{
private RedisCache $cache;
private int $maxRequests;
private int $windowSeconds;
public function __construct(int $maxRequests = 100, int $windowSeconds = 60)
{
$this->cache = new RedisCache(
'localhost', 6379, null, 0,
'rate_',
$windowSeconds
);
$this->maxRequests = $maxRequests;
$this->windowSeconds = $windowSeconds;
}
public function isAllowed(string $identifier): bool
{
$key = "limit_{$identifier}";
$current = $this->cache->get($key, 0);
if ($current >= $this->maxRequests) {
return false;
}
$this->cache->set($key, $current + 1, $this->windowSeconds);
return true;
}
}
// Usage
$limiter = new RateLimiter(100, 60);
$clientIp = $_SERVER['REMOTE_ADDR'];
if (!$limiter->isAllowed($clientIp)) {
http_response_code(429);
die('Too Many Requests');
}3. Using with CacheFactory
use Kotchasan\Cache\CacheFactory;
// Create RedisCache via Factory
$cache = CacheFactory::create([
'driver' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
'password' => 'secret',
'database' => 0,
'prefix' => 'myapp_'
]);
$cache->set('key', 'value', 3600);Best Practices
1. Use Meaningful Prefixes
$userCache = new RedisCache('localhost', 6379, null, 0, 'user_');
$sessionCache = new RedisCache('localhost', 6379, null, 0, 'session_');2. Check Connection Before Use
$cache = new RedisCache('localhost', 6379);
if (!$cache->isAvailable()) {
$cache = new MemoryCache(); // Fallback
}Warnings
⚠️ Warning:
- Ensure Redis server is running
- Use password for production
- Be careful with
clear()in shared environments
Related Classes
- CacheFactory - Create cache instances
- [FileCache] - File-based cache
- MemoryCache - Memory Cache
- QueryCache - Query Cache