1. Go to this page and download the library: Download iprodev/php-easycache library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
iprodev / php-easycache example snippets
use Iprodev\EasyCache\Cache\MultiTierCache;
use Iprodev\EasyCache\Storage\ApcuStorage;
use Iprodev\EasyCache\Storage\RedisStorage;
use Iprodev\EasyCache\Storage\FileStorage;
use Iprodev\EasyCache\Serialization\NativeSerializer;
use Iprodev\EasyCache\Compression\GzipCompressor;
// Tiers: APCu -> Redis -> File
$apcu = new ApcuStorage('ec:');
// phpredis (example); predis is also supported
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redisStore = new RedisStorage($redis, 'ec:');
$file = new FileStorage(__DIR__.'/cache');
$cache = new MultiTierCache(
[$apcu, $redisStore, $file],
new NativeSerializer(),
new GzipCompressor(3),
defaultTtl: 600
);
// PSR-16 API
$cache->set('user_42', ['id'=>42, 'name'=>'Ava'], 300);
$data = $cache->get('user_42'); // ['id'=>42, 'name'=>'Ava']
// Example: Memory -> Redis -> Database
$cache = new MultiTierCache(
[
new ApcuStorage('app:'), // Fast: In-memory
new RedisStorage($redis), // Medium: Network cache
new PdoStorage($pdo, 'cache') // Slow: Database fallback
],
new NativeSerializer(),
new NullCompressor(),
3600 // 1 hour default TTL
);
$result = $cache->getOrSetSWR(
key: 'posts_homepage',
producer: function () {
// Expensive API call or database query
return fetchPostsFromDatabase();
},
ttl: 300, // 5 minutes of fresh data
swrSeconds: 120, // Serve stale up to 2 minutes after expiry
staleIfErrorSeconds: 600, // If refresh fails, serve stale up to 10 minutes
options: ['mode' => 'defer'] // Defer refresh until after response
);
// PHP Native Serializer (supports objects)
use Iprodev\EasyCache\Serialization\NativeSerializer;
$cache = new MultiTierCache([$storage], new NativeSerializer());
// JSON Serializer (portable, faster for simple data)
use Iprodev\EasyCache\Serialization\JsonSerializer;
$cache = new MultiTierCache([$storage], new JsonSerializer());
// No compression
use Iprodev\EasyCache\Compression\NullCompressor;
$cache = new MultiTierCache([$storage], $serializer, new NullCompressor());
// Gzip compression (balanced)
use Iprodev\EasyCache\Compression\GzipCompressor;
$cache = new MultiTierCache([$storage], $serializer, new GzipCompressor(5));
// Zstd compression (fastest)
use Iprodev\EasyCache\Compression\ZstdCompressor;
$cache = new MultiTierCache([$storage], $serializer, new ZstdCompressor(3));
use Iprodev\EasyCache\Storage\ApcuStorage;
$storage = new ApcuStorage(
prefix: 'myapp:' // Namespace your keys
);
use Iprodev\EasyCache\Storage\RedisStorage;
// Using phpredis
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$storage = new RedisStorage($redis, 'myapp:');
// Using predis
$redis = new Predis\Client('tcp://127.0.0.1:6379');
$storage = new RedisStorage($redis, 'myapp:');
use Iprodev\EasyCache\Storage\PdoStorage;
$pdo = new PDO('mysql:host=localhost;dbname=cache', 'user', 'pass');
$storage = new PdoStorage($pdo, 'easycache');
// Create table (run once during setup)
$storage->ensureTable();
use Iprodev\EasyCache\Cache\MultiTierCache;
use Iprodev\EasyCache\Storage\FileStorage;
use Iprodev\EasyCache\Serialization\NativeSerializer;
use Iprodev\EasyCache\Compression\NullCompressor;
$storage = new FileStorage(__DIR__ . '/cache');
$cache = new MultiTierCache([$storage], new NativeSerializer(), new NullCompressor());
// Set with 1 hour TTL
$cache->set('user_profile', [
'id' => 123,
'name' => 'John Doe',
'email' => '[email protected]'
], 3600);
// Get
$profile = $cache->get('user_profile');
// Check existence
if ($cache->has('user_profile')) {
echo "Profile is cached!";
}
// Delete
$cache->delete('user_profile');
// Setup: APCu (fast) -> Redis (medium) -> File (slow)
$apcu = new ApcuStorage('app:');
$redis = new RedisStorage($redisClient, 'app:');
$file = new FileStorage('/var/cache/app');
$cache = new MultiTierCache([$apcu, $redis, $file]);
// First request: Cache miss, data fetched and stored in all tiers
$data = $cache->get('expensive_data');
// APCu crashes and restarts...
// Next request: Data found in Redis, automatically backfilled to APCu
$data = $cache->get('expensive_data'); // Fast!
use Psr\Log\LoggerInterface;
$cache = new MultiTierCache(
[$apcu, $redis],
new NativeSerializer(),
new GzipCompressor(5),
600, // 10 min default TTL
$logger // Optional PSR-3 logger
);
$posts = $cache->getOrSetSWR(
key: 'api_posts_latest',
producer: function() use ($apiClient) {
// This is expensive
return $apiClient->fetchPosts();
},
ttl: 300, // Fresh for 5 minutes
swrSeconds: 60, // Serve stale for 1 minute while refreshing
staleIfErrorSeconds: 300, // Serve stale for 5 minutes if API fails
options: ['mode' => 'defer'] // Refresh after response sent
);
// Cache for 2 hours
$cache->set('key', 'value', new DateInterval('PT2H'));
// Cache for 1 day
$cache->set('key', 'value', new DateInterval('P1D'));
// Cache for 30 days
$cache->set('key', 'value', new DateInterval('P30D'));
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('cache');
$logger->pushHandler(new StreamHandler('/var/log/cache.log', Logger::WARNING));
$cache = new MultiTierCache(
[$storage],
new NativeSerializer(),
new NullCompressor(),
3600,
$logger // Will log warnings and errors
);
// Run this in a cron job or scheduled task
$pruned = $cache->prune();
echo "Pruned {$pruned} expired items";
// For PDO storage, this removes expired rows
// For File/APCu/Redis, expiration is automatic