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