Remote file cache with interval updates with PHP

3

I'm developing a news portal and I'm using a Weather API . The problem is that every time people open the page, PHP downloads the API JSON , and this interferes with page loading speed.

In order to solve this problem and save bandwidth, I thought about caching this JSON and downloading updates in a 15-minute interval, but I have no idea where to start.

Can you help me? Thank you in advance.

    
asked by anonymous 16.01.2016 / 18:55

1 answer

1

What you need to do is use a caching system such as memcached . In your code in which you get JSON you do a conditional check that sees if this JSON is already stored in the cache, if you just get it from there (which is an instant operation since the cache will generally store in RAM), if the JSON is not present you get 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
    
17.01.2016 / 17:18