PHP code example of tweekersnut / cache

1. Go to this page and download the library: Download tweekersnut/cache 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/ */

    

tweekersnut / cache example snippets




weekersNut\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' => '[email protected]'], 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();

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');

$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
]);

$cache = Cache::make([
    'driver' => 'file',
    'path' => '/var/www/cache',  // Cache directory
    'prefix' => 'myapp:',        // Optional
    'ttl' => 3600                // Optional default TTL
]);

$cache = Cache::make([
    'driver' => 'session',
    'prefix' => 'cache:',        // Optional
    'ttl' => 1800                // Optional default TTL
]);

$cache = Cache::make([
    'driver' => 'array',
    'prefix' => 'temp:',         // Optional
    'ttl' => 300                 // Optional default TTL
]);

$user = $cache->get('user:1');
$user = $cache->get('user:1', ['name' => 'Guest']); // With default

$cache->set('user:1', $userData, 600); // Expires in 600 seconds
$cache->set('permanent', $data);       // No expiration

if ($cache->has('user:1')) {
    // Key exists
}

$cache->delete('user:1');

$cache->clear();

$users = $cache->remember('all_users', 600, function() {
    return User::all(); // Heavy database query
});

$views = $cache->increment('page_views');
$views = $cache->increment('page_views', 10);

$remaining = $cache->decrement('api_quota');

use TweekersNut\Cache\Cache;

function getUsers() {
    return Cache::remember('users:all', 600, function() {
        // This query only runs if cache is empty
        return $db->query("SELECT * FROM users")->fetchAll();
    });
}

function getWeatherData($city) {
    $key = "weather:{$city}";
    
    return Cache::remember($key, 1800, function() use ($city) {
        // API call only happens if not cached
        $response = file_get_contents("https://api.weather.com/{$city}");
        return json_decode($response, true);
    });
}

function checkRateLimit($userId) {
    $key = "rate_limit:{$userId}";
    $requests = (int) Cache::get($key, 0);
    
    if ($requests >= 100) {
        throw new Exception("Rate limit exceeded");
    }
    
    Cache::increment($key);
    
    if ($requests === 0) {
        Cache::set($key, 1, 3600); // Reset after 1 hour
    }
}

function calculateStatistics() {
    return Cache::remember('daily_stats', 86400, function() {
        // Expensive computation
        $stats = [
            'total_users' => countUsers(),
            'total_orders' => countOrders(),
            'revenue' => calculateRevenue()
        ];
        return $stats;
    });
}

$sessionCache = Cache::make(['driver' => 'session']);

// Store user preferences
$sessionCache->set('user_theme', 'dark');
$sessionCache->set('user_language', 'en');

// Retrieve
$theme = $sessionCache->get('user_theme', 'light');

$cache = Cache::make([
    'driver' => 'redis',
    'prefix' => 'myapp:v1:'
]);

$cache->set('users', $data); // Actually stored as "myapp:v1:users"

// Fast cache for frequent access
$fastCache = Cache::make(['driver' => 'redis']);

// Persistent cache for less frequent data
$persistentCache = Cache::make(['driver' => 'file']);

$fastCache->set('hot_data', $data, 60);
$persistentCache->set('cold_data', $data, 86400);

try {
    $cache = Cache::make(['driver' => 'redis']);
} catch (\Exception $e) {
    // Fallback to file cache if Redis unavailable
    $cache = Cache::make(['driver' => 'file']);
}