Cache a slow result
Some values are slow to get, for example an exchange rate from another service. This program computes the value once and reads it from a cache after that.
<?nvs// This program saves a slow result in a cache, so the next call is fast.class Rates{ // Returns the exchange rate. Only the first call in one hour computes it. public static function euroToDollar(): float { var $cache = Core\Cache::memory(); var $saved = $cache->get('eur-usd'); if ($saved != null) { echo "from the cache\n"; return $saved as float; } echo "computed\n"; // A real program would call a slow service here. float $rate = 1.08; // `ttl` is how long the value stays in the cache. $cache->put('eur-usd', $rate, { ttl: 1h }); return $rate; }}
// The first call prints `computed`. The second call prints `from the cache`.echo Rates::euroToDollar(), "\n";echo Rates::euroToDollar(), "\n";computed1.08from the cache1.08$cache->get returns null when the key is not in the cache. The method then computes the value
and writes it with put. ttl is how long the value stays. After one hour, the next call
computes it again.
Core\Cache::memory keeps the value in the memory of this server process. Every request on this
server finds it. A restart empties the cache, and another server does not see it. For a value that
all your servers must see, use Core\Cache::shared.
Read Core\Cache for the two kinds of cache.
