0

I'm currently building a little application using Laravel and want to show the weather on the dashboard. To do that I use a Composer package that accesses the Forecast.io API. However, since that API has a rate limit on free calls per day I would like to cache the data using the Laravel facilities and just update it every few minutes.

To do that I could think of two ways:

  1. Create a custom class that checks the cache for data before polling and just letting the cache data expire after x minutes.
  2. Create a cronjob in Laravel that just regularly updates the weather data in the cache.

From my point of view the first option seems to be the better one as it guarantees I will always have data available, even if the cache is emptied. Apart from that it just seems cleaner.

Problem is: I have no clue how to implement such a class in Laravel and couldn't find anything in the official docs either. My wish would be that I could simply call a Facade which gives me the data and the rest is handled in the background. I just need to know where to put such a Facade and how to set it up.

Regards,

Heiko

Heiko Rothe
  • 331
  • 3
  • 16

1 Answers1

1

You don't even need a Class for that just use

$weather = Cache::remember('weather', $minutes, function() {
    // Your API call
    return $weather;
});

You can see the doc here https://laravel.com/docs/5.2/cache#retrieving-items-from-the-cache

The down side of this method is that your user will wait for the API call if the cache is empty...

You can still use a cron if you want to just store the value in the cache then retrieve it.

Elie Faës
  • 3,215
  • 1
  • 25
  • 41
  • Oh wow, I totally missed the remember function while looking through the docs, thanks for the hint. Does the caching system handle arrays fine? I haven't seen anything about that either. EDIT: Nevermind, it does. The example in that section of the logs literally proves it, haha. Thank you for that great hint! – Heiko Rothe Mar 13 '16 at 22:03
  • No problem ;) the Cache stuff can store almost everything like arrays, strings, integers, classes, .... (as long as your class have `__sleep` and `__wakeup` method) – Elie Faës Mar 13 '16 at 22:10