琴独奏 / 天气包
Symfony的天气包
v2.1.0
2017-07-31 15:43 UTC
Requires
- php: >=5.3.9
- guzzlehttp/guzzle: ^6.2
- symfony/symfony: ~2.7|~3.0
Requires (Dev)
- phpunit/phpunit: ~4.0
This package is not auto-updated.
Last update: 2024-09-19 11:43:41 UTC
README
琴独奏天气包是一个用于从天气服务获取数据的Symfony2项目。目前可以获取来自OpenWeatherMap API的数据。琴独奏天气包提供了在项目中使用天气数据的不同方式。一种是通过Twig扩展,另一种是通过服务,该服务将API的所有天气信息作为对象提供。
安装
1-) 运行以下命令,让composer下载:
composer require pianosolo/weather-bundle
2-) 将包添加到AppKernel
<?php // app/AppKernel.php public function registerBundles() { $bundles = array( // ... new PianoSolo\WeatherBundle\PianoSoloWeatherBundle(), ); }
3-) 将配置添加到config.yml文件
piano_solo_weather: api_key: "YourApiKey" # Required (OpenWeatherMap Api Key) options: download_csv: false # Default True cache: true # Default False (To use cache the system needs Php-Apc cache)
要安装Php-Apc,运行此命令:
sudo apt-get install php-apc
4-) 将CSV下载的路由添加到routing.yml
pianosolo_weather: resource: "@PianoSoloWeatherBundle/Resources/config/routing.yml"
使用方法
基本使用
从OpenWeatherMap API获取数据。检查API使用方法:http://openweathermap.org/api
通过类型获取数据。在数组中添加URL参数。
$weatherService = $this->get('pianosolo.weather'); $weather = $weatherService->getData('forecast', array('id' => 800, 'lat' => 52.52, 'lon' => 13.41));
或通过城市名称和类型获取数据
$weatherService = $this->get('pianosolo.weather'); $weather = $weatherService->getCityData('weather', 'Berlin', array('param' => 'value'));
作为Twig扩展
将每日天气预报以bootstrap表格格式化的HTML形式呈现。
{{ pianosolo_get_forecast('Istanbul', 5) }}
这展示了伊斯坦布尔的5天天气信息(日期、城市、温度、描述)
{{ pianosolo_get_weather('Istanbul') }}
这展示了伊斯坦布尔的1天天气结果(日期、城市、温度、描述)
作为天气服务
1-) 获取标准类对象作为天气响应
$weatherService = $this->get('pianosolo.weather'); $weather = $weatherService->getWeather('Istanbul');
2-) 获取天气对象
$weatherService = $this->get('pianosolo.weather'); $weathersArray = $weatherService->getWeatherObject('Istanbul'); $weatherObject = $weathersArray[0]; $city = $WeatherObject->getCity(); $date = $WeatherObject->getWdate(); $temperature = $WeatherObject->getTemperature(); $description = $WeatherObject->getDescription();
3-) 获取标准类对象作为天气预报响应
$weatherService = $this->get('pianosolo.weather'); $weather = $weatherService->getForecast('Istanbul', 2); // 2 days weather results of the city
4-) 获取天气对象数组作为天气预报
$weatherService = $this->get('pianosolo.weather'); $weathersArray = $weatherService->getForecastObject('Istanbul',2); foreach($weathersArray as $weatherObject){ $city = $WeatherObject->getCity(); $date = $WeatherObject->getWdate(); $temperature = $WeatherObject->getTemperature(); $description = $WeatherObject->getDescription(); // Your Logic... }