TweekersNut Cache
๐ฆ Installation
Install via Composer:
composer require tweekersnut/cache
Requirements
- PHP >= 8.0
- (Optional) Redis extension for Redis driver
- (Optional) Predis library as alternative to Redis extension
๐ฏ Quick Start
Basic Usage
<?php
require 'vendor/autoload.php';
use TweekersNut\Cache\Cache;
// Create a cache instance
$cache = Cache::make([
'driver' => 'file',
'path' => '/path/to/cache',
'prefix' => 'myapp:',
'ttl' => 3600
]);
// Store data
$cache->set('user:1', ['name' => 'John Doe', 'email' => 'john@example.com'], 600);
// Retrieve data
$user = $cache->get('user:1');
// Check if key exists
if ($cache->has('user:1')) {
echo "User found in cache!";
}
// Delete a key
$cache->delete('user:1');
// Clear all cache
$cache->clear();
Static Facade Usage
use TweekersNut\Cache\Cache; // Configure once Cache::setInstance(Cache::make(['driver' => 'redis', 'host' => '127.0.0.1'])); // Use anywhere Cache::set('key', 'value', 300); $value = Cache::get('key');
๐ง Configuration
Redis Driver
$cache = Cache::make([
'driver' => 'redis',
'host' => '127.0.0.1',
'port' => 6379,
'password' => 'secret', // Optional
'database' => 0, // Optional (default: 0)
'timeout' => 2.5, // Optional (default: 2.5)
'prefix' => 'myapp:', // Optional
'ttl' => 3600 // Optional default TTL
]);
Requirements: PHP Redis extension (ext-redis) or Predis library
Best For: High-traffic applications, distributed systems, shared cache across servers
File Cache Driver
$cache = Cache::make([
'driver' => 'file',
'path' => '/var/www/cache', // Cache directory
'prefix' => 'myapp:', // Optional
'ttl' => 3600 // Optional default TTL
]);
Best For: Single-server applications, development, when Redis is unavailable
Session Cache Driver
$cache = Cache::make([
'driver' => 'session',
'prefix' => 'cache:', // Optional
'ttl' => 1800 // Optional default TTL
]);
Best For: Per-user caching, temporary user-specific data
Array (Memory) Cache Driver
$cache = Cache::make([
'driver' => 'array',
'prefix' => 'temp:', // Optional
'ttl' => 300 // Optional default TTL
]);
Best For: Testing, single-request caching, temporary runtime data
๐ Driver Comparison
| Feature | Redis | File | Session | Array |
|---|---|---|---|---|
| Persistence | โ Yes | โ Yes | โ ๏ธ Session only | โ No |
| Multi-Server | โ Yes | โ No | โ No | โ No |
| Performance | โก Excellent | โ ๏ธ Good | โ ๏ธ Good | โก Excellent |
| Setup Required | โ Redis server | โ None | โ None | โ None |
| Memory Usage | โ ๏ธ External | โ ๏ธ Disk | โ ๏ธ Session | โ ๏ธ PHP memory |
| Best For | Production | Development | User data | Testing |