uberboom/forecast

dev-master 2014-05-02 05:58 UTC

This package is not auto-updated.

Last update: 2024-09-28 16:20:34 UTC


README

PHP 的 Forecast.io API

  • 框架无关
  • 内置 Laravel 支持
  • 缓存支持以减少 API 调用
  • 如果需要,提供自己的缓存存储和 HTTP 客户端

在 Laravel 4 中使用 Forecast

应用配置

您可以将 ForecastServiceProvider 注册以自动使用 Laravel 内置的缓存功能。

要这样做,请更新您的 app/config/app.php 文件中的 providers 数组

'providers' => array(
	// ...
	'Uberboom\Forecast\ForecastServiceProvider',
),

接下来,更新 app/config/app.php 文件中的 aliases 数组中的类别名

'providers' => array(
	// ...
	'Forecast' => 'Uberboom\Forecast\Facades\Forecast',
),

配置

首先,从包中发布配置

php artisan config:publish uberboom/forecast

API 密钥

Forecast for Developers 获取 API 密钥,并将其添加到 app/config/packages/uberboom/forecast/config.php 文件中

'api_key' => 'your-api-key-from-developer.forecast.io',

配置 HTTP 客户端

该包包含两个不同的 HTTP 客户端实现:一个是使用 PHP Curl 扩展,另一个依赖于 file_get_contents(),所以请确保已加载 Curl 扩展或已在您的 php.ini 文件中启用了 allow_url_fopen

'httpclient' => 'curl|file',

检索天气预报

该包提供了一些 Laravel Facade 魔法,因此获取天气预报非常简单

$weather = \Forecast::getWeatherByLocation($latitude, $longitude);

如果您需要更改单位,您可以通过使用 setUnits() 方法来设置响应中使用的单位

$weather = \Forecast::setUnits(\Uberboom\Forecast\Forecast::UNITS_SI)->getWeatherByLocation($latitude, $longitude);

未使用 Laravel?

手动配置

如果您没有使用 Laravel,则必须手动设置 API 密钥

$forecastApiKey = 'your-api-key-from-developer.forecast.io';
$forecast = new \Uberboom\Forecast\Forecast();
$forecast->setApiKey($forecastApiKey);

设置 HTTP 客户端

该包包含两个不同的 HTTP 客户端实现:一个是使用 PHP Curl 扩展,另一个依赖于 file_get_contents,所以请确保已加载 Curl 扩展或已在您的 php.ini 文件中启用了 allow_url_fopen

$forecast->setHttpClientWrapper(new \Uberboom\Forecast\HttpClient\Curl());
$forecast->setHttpClientWrapper(new \Uberboom\Forecast\HttpClient\File());

缓存

目前,该包仅包括 Laravel 框架的缓存存储实现。如果您想使用包的缓存功能,则需要构建并注入自己的缓存存储类,该类必须实现 \Uberboom\Forecast\CacheStore\CacheStoreInterface 接口。

$forecast->setCacheStore(new YourCacheStore());

检索天气预报

$forecast->getWeatherByLocation($latitude, $longitude);

如果您需要更改单位,您可以通过使用 setUnits() 方法来设置响应中使用的单位

$weather = $forecast::setUnits(\Uberboom\Forecast\Forecast::UNITS_SI)->getWeatherByLocation($latitude, $longitude);

待办事项

  • 改进 API 文档
  • 提供单元测试