Remote file cache with interval updates with PHP

Asked

Viewed 94 times

3

I’m developing a news portal and I’m using a Weather forecast API. The problem is that every time people open the page, PHP downloads the JSON of the API, and this ends up interfering with the page load speed.

In order to solve this problem and save bandwidth, I thought I’d cache this JSON and download updates in a 15-minute interval, but I have no idea where to start.

Can you help me? Thanks in advance.

1 answer

1

What you need is to use a caching system like the memcached. In your code that picks up the JSON you make a conditional check that sees if this JSON is already stored in the cache, if you are just take it from there (which is an instantaneous operation since usually the cache will store in RAM)If JSON is not present, you take it from the external server and store it in the cache. In code it’s going to be something like this:

$memcached = new Memcached('pool');

$data = $memcached->get('alguma_previsao');
if ($data === Memcached::RES_NOTFOUND) { // dados não estão no cache
    $data = getJSONdoServidorExterno(); // aqui você pega o JSON como já faz normalmente

    $memcached->add('alguma_previsao', $data, 60 * 15); // armazena o JSON por 15 minutos no cache (60 segundos * 15)
}
$jsonFinal = $data; // aqui você tem o JSON de que precisa

Browser other questions tagged

You are not signed in. Login or sign up in order to post.