PHP code example of elephant-php / ttl
1. Go to this page and download the library: Download elephant-php/ttl 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/ */
elephant-php / ttl example snippets
/** @var \Psr\SimpleCache\CacheInterface $psrCache */
$cache = new Cache();
use Elephant\Ttl\Ttl;
$cache = new Cache();
$cache->set('key1', 'value1', Ttl::seconds(30)->toSeconds()); // 30 seconds
$cache->set('key2', 'value2', Ttl::minutes(15)->toSeconds()); // 15 minutes
$cache->set('key3', 'value3', Ttl::hours(2)->toSeconds()); // 2 hours
$cache->set('key4', 'value4', Ttl::days(1)->toSeconds()); // 1 day
// Complex durations
$ttl = Ttl::create(sec: 30, min: 10, hour: 1); // 1 hour 10 minutes 30 seconds
$cache->set('key', 'value', $ttl->toSeconds());
// Infinity / no expiration
$cache->set('key6', 'value6', Ttl::forever()); // shorthand for null
$cache->set('key7', 'value7', Ttl::from(null));
$ttl = Ttl::from(new DateInterval('PT45M')); // 45 minutes
$ttl = Ttl::from(10); // 10 seconds
$ttl = Ttl::from('12'); // 12 seconds
$ttl = Ttl::from(null); // Infinity / no expiration
$ttl = Ttl::from(Ttl::seconds(500));
$ttl = Ttl::create(sec: 30, min: 15);
// From DateInterval
$ttl = Ttl::fromInterval(new DateInterval('PT45M'));
$cache->set('key', 'value', $ttl->toSeconds());
// Ttl::forever() is just a shorthand for `null` TTL (no expiration)
$cache->set('key', 'value', Ttl::forever()->toSeconds());
// or
$cache->set('key', 'value', Ttl::from(null)->toSeconds());
use Your\Cache\Cache;
use Your\Cache\ArrayCache;
use Elephant\Ttl\Ttl;
$cache = new Cache(new ArrayCache(), Ttl::minutes(5)); // default TTL
$cache->getOrSet('key', 'value'); // // Uses default TTL
// Custom TTL
$cache->getOrSet('key2', fn() => 'value2', Ttl::seconds(30)->toSeconds());
$cache->getOrSet('key3', fn() => 'value3', Ttl::forever()->toSeconds()); // No expiration
if (Ttl::from(null)->isForever()) {
// No expiration
}
$ttl = Ttl::seconds(60);
$seconds = $ttl->toSeconds(); // Returns 60
$seconds = $ttl->value; // Also 60
$ttl = Ttl::from('abc'); // Converts to 0 (expired)
$ttl = Ttl::from(1.5); // TypeError: invalid TTL type
shell
composer