Skip to content

Cached External Content

JP Barbosa edited this page Mar 22, 2021 · 7 revisions

Cached External Content

Create model Api
nano app/WeatherApi.php
<?php

namespace App;

use Cache;
use Carbon\Carbon;

class WeatherApi
{

    public function data()
    {
        return Cache::get('Weather.reads') ?: $this->update();
    }

    public function update($urlApi = null)
    {
        if (is_null($urlApi)) {
            $urlApi = 'https://api.openweathermap.org/data/2.5/weather?q=Sao%20Paulo,br&units=metric&APPID=' . getenv('WEATHER_APPID');
        }

        $json = file_get_contents($urlApi);
        $response = json_decode($json);
        $data = $response->main;
        $data->updated_at = Carbon::now()->toDateTimeString();

        Cache::forever('Weather.reads', $data);

        return $data;
    }
}
Generate weather service provider
php artisan make:provider WeatherProvider
Add api data in the partial
nano app/Providers/WeatherProvider.php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\WeatherApi;

class WeatherProvider extends ServiceProvider
{
    public function boot()
    {
        view()->composer('shared.nav', function ($view) {
            $data = (new WeatherApi)->data();
            $view->with('weather', $data);
        });
    }
    ...
}
Add weather service provider in the app
nano config/app.php
'providers' => [
        ...
        App\Providers\WeatherProvider::class,
    ],
Change weather placeholder to use PHP array
nano resources/views/shared/nav.blade.php
<li class="navbar-text">
    Sao Paulo: {{ $weather->temp }} Celsius.
    Last update {{ $weather->updated_at }}
</li>
Comment out load weather by ajax
nano resources/assets/js/loadRemoteContent.js
...
//$(function() {
//    loadWeather();
//});
gulp
Generate command to update weather
php artisan make:console WeatherUpdate --command=weather:update
Update description and call WeatherApi
nano app/Console/Commands/WeatherUpdate.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\WeatherApi;

class WeatherUpdate extends Command
{
    ...

    protected $description = 'Update weather data.';

    ...

    public function handle()
    {
        $api = new WeatherApi;
        $data = $api->update();
        echo json_encode($data) . PHP_EOL;
    }
}
Schedule weather update command
nano app/Console/Kernel.php
<?php
...
class Kernel extends ConsoleKernel
{
    protected $commands = [
        ...
        \App\Console\Commands\WeatherUpdate::class,
    ];

    protected function schedule(Schedule $schedule)
    {
        ...
        $schedule->command('weather:update')
                 ->hourly();
    }
}
Test weather update
php artisan weather:update
{"temp":20.54,"pressure":1020,"humidity":72,"temp_min":20,"temp_max":21,"updated_at":"2015-07-07 17:41:04"}
Start the server
php artisan serve
Open any page in the browser and check for weather info
open http://localhost:8000
Set redis as default cache driver on envioriment variables and set WEATHER_APPID
nano .env
CACHE_DRIVER=redis
...
WEATHER_APPID=YOUR_WEATHER_APPID
Run redis server
redis-server
Restart the server
php artisan serve
Check again
open http://localhost:8000
Add cached external content to Git
git add .
git commit -m "Add cached external content"
Next step: Tests Setup
Clone this wiki locally