-
Notifications
You must be signed in to change notification settings - Fork 49
Cached External Content
JP Barbosa edited this page Mar 22, 2021
·
7 revisions
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;
}
}
php artisan make:provider WeatherProvider
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);
});
}
...
}
nano config/app.php
'providers' => [
...
App\Providers\WeatherProvider::class,
],
nano resources/views/shared/nav.blade.php
<li class="navbar-text">
Sao Paulo: {{ $weather->temp }} Celsius.
Last update {{ $weather->updated_at }}
</li>
nano resources/assets/js/loadRemoteContent.js
...
//$(function() {
// loadWeather();
//});
gulp
php artisan make:console WeatherUpdate --command=weather:update
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;
}
}
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();
}
}
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"}
php artisan serve
open http://localhost:8000
nano .env
CACHE_DRIVER=redis
...
WEATHER_APPID=YOUR_WEATHER_APPID
redis-server
php artisan serve
open http://localhost:8000
git add .
git commit -m "Add cached external content"
Next step: Tests Setup
- Setup
- Basic CRUD
- Validation
- Views
- Association
- Association Controller
- Association Views
- Basic Template
- Bootstrap
- Bootstrap CRUD
- Alerts
- Welcome Page
- Ajax CRUD
- Send Email
- Send Email Views
- Jobs Queue
- Captcha
- Async External Content
- Cached External Content
- Tests Setup
- Functional Tests
- Acceptance Tests
- Continuous Integration
- Deploy with Heroku
- Deploy with Forge
- Update README