PHP code example of kielabokkie / uber-cache

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

    

kielabokkie / uber-cache example snippets


// data is fetched from the external API and cached for 1 minute
$todo = UberCache::remember('key', now()->addMinute(), now()->addHour(), function () {
    return Http::get('https://jsonplaceholder.typicode.com/todos/1')->json();
});

dump($todo);

/**
{
    id: 1,
    title: "delectus aut autem",
    completed: false
}
*/

// -- 5 minutes later --

// cache is expired so should fetch from API but API is down
$todo = UberCache::remember('key', now()->addMinute(), now()->addHour(), function () {
    throw new \Exception('API error');
});

// the todo still returns the previously expired cache
dump($todo);

/**
{
    id: 1,
    title: "delectus aut autem",
    completed: false
}
*/

// -- 2 hours later --

// cache is expired and max cache time also expired but API is still down
$todo = UberCache::remember('key', now()->addMinute(), now()->addHour(), function () {
    throw new \Exception('API error');
});

// an UberCacheException is thrown

$value = Cache::remember('todos', now()->addMinute(), function () {
    return Http::get('https://jsonplaceholder.typicode.com/todos/1')->json();
});

$value = UberCache::remember('todos', now()->addMinute(), now()->addHour(), function () {
    return Http::get('https://jsonplaceholder.typicode.com/todos/1')->json();
});