Search code examples
phplaravellaravel-5laravel-facade

How to create a custom data retrieval class in Laravel?


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


Solution

  • 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.