在云中构建天气跟踪应用程序,第 2 部分

WBOY
Release: 2016-06-23 13:11:28
Original
983 people have browsed it

在第 1 部分 中,我介绍了如何创建一个基础 PHP 应用程序,并使用一个在线服务检索并存储世界城市的经纬度坐标。

现在让我们添加来自 IBM 的新 Insights for Weather 服务,并开始使用来自第 1 部分的城市信息跟踪您选择的 5 个世界城市的天气。您还将了解如何将您的最终应用程序托管在 IBM Bluemix 上。

运行示例应用程序

获取示例应用程序的代码

观看 Vikram 逐步演示代码

抄本

完成您的应用程序的前提条件

参见第 1 部分 了解必备知识和软件。

第 1 步. 初始化一个 Insights for Weather Service 实例

因为存储数据库中的每个位置记录还包含该位置的纬度和经度,所以您现在可以将您的应用程序与 Insights for Weather 服务相集成。最初,此服务实例将在一种未绑定状态下运行;这使您能够在本地开发应用程序,而将服务实例本身远程托管在 Bluemix 上。

阅读: Insights for Weather 入门

  1. 要创建一个新 Insights for Weather 实例,可以登录到您的Bluemix 帐户,在仪表板中单击 Use Services or APIs 按钮。从得到的服务列表中选择 Insights for Weather

  2. 检查该服务的描述并单击 CREATE 来启动它。确保 App 字段被设置为 Leave unbound ,而且您使用的是 Free Plan

  3. 该服务实例现在将被初始化,您会看到一个服务信息页面。记下服务名称,您在需要使用它。左侧会显示一个导航栏,单击 Service Credentials 查看该服务实例的访问细节。

  4. 将 url 字段的内容复制到应用程序的 $APP_ROOT /config.php 文件中的 weather_uri 键中。这使您的应用程序能够连接到远程 Insights for Weather 实例并开始从中检索天气数据。

第 2 步. 显示当前天气数据

  1. 要使用 Insights for Weather 服务,只需请求上一节中显示的服务 URL 并向它附加 API 签名。例如,一个针对 API 端点 https://USERNAME:PASSWORD@twcservice.mybluemix.net/api/weather/v2/observations/current?units=m&language=en-US&geocode=51.50853-0.12574 的请求将生成以下响应,该响应显示了伦敦的当前天气:  
  2. 具体地讲,JSON 输出包括当前天气的描述性短语(例如 “Partly cloudy”),以及当前温度、风速、湿度和其他数据。要在您的应用程序中显示同样的信息,可以更新 /index 路由处理函数来检索存储的位置列表;然后连接到上面显示的 Insights for Weather 服务来检索每个位置的当前天气条件:
    <?php// index page handlers$app->get('/', function () use ($app) {  return $app->redirect($app["url_generator"]->generate('index'));});$app->get('/index', function () use ($app, $db) {  // get list of locations from database  // for each location, get current weather from Weather service  $collection = $db->locations;    $locations = iterator_to_array($collection->find());  foreach ($locations as &$location) {    $uri = $app->config['weather_uri'] . '/api/weather/v2/observations/current?units=m&language=en-US&geocode=' . urlencode(sprintf('%f,%f', $location['lat'], $location['lng']));    $json = file_get_contents($uri);    if ($json === FALSE) {     throw new Exception("Could not connect to Weather API.");      }    $location['weather'] = json_decode($json, true);  }  return $app['twig']->render('index.twig', array('locations' => $locations));})->bind('index');
    Copy after login
  3. 接下来,更新 $APP_ROOT /views/index.twig 上的 Twig 模板以显示此信息:
    <div data-role="content">               <h2 class="ui-bar ui-bar-a">Current Weather</h2>        <div class="ui-body">          <ul data-role="listview" data-split-icon="minus" data-split-theme="d">                    {% for item in locations %}            <li>              <a href="{{ app.url_generator.generate('forecast', {'id': item._id|trim}) }}" data-ajax="false">{{ item.location }}, {{ item.country }}              <br/>              {{ item.weather.observation.metric.temp }}&deg; C | {{ item.weather.observation.phrase_22char }}              </a>              <a href="{{ app.url_generator.generate('delete', {'id': item._id|trim}) }}" data-ajax="false">Remove</a>                             </li>          {% endfor %}          </ul>        </div>                     <div>          <p><a href="{{ app.url_generator.generate('search') }}" data-ajax="false" data-inline="true" data-role="button" data-icon="plus" data-theme="a">Add Location</a></p>        </div>                   </div>
    Copy after login
  4. 这是该模板的外观。如果更喜欢使用图标代替文本,Insights for Weather 服务提供了一组完整的图标,以及如何使用它们的 说明 。

请注意,每个位置的旁边都有一个 Delete 按钮,它链接到 /delete 路由处理函数,并将该位置的唯一 MongoDB 记录标识符传递给此处理函数。 /delete 处理函数将从 MongoDB 数据库中删除指定的记录:

<?php// handler to remove location from database$app->get('/delete/{id}', function ($id) use ($app, $db) {  $collection = $db->locations;  $collection->remove(array('_id' => new MongoId($id)));  return $app->redirect($app["url_generator"]->generate('index'));})->bind('delete');
Copy after login

第 3 步. 检索天气预报

  1. 就像您可以检索任何位置的当前天气条件一样,Insights for Weather 服务还允许您检索该位置的 10 天内的天气预报。将您的 API 请求更新为 https://USERNAME:PASSWORD@twcservice.mybluemix.net/api/weather/v2/forecast/daily/10day?units=m&language=en-US&geocode=51.50853-0.12574 ,您将收到白天和晚上的天气条件的详细信息,如下所示。请注意输入中的 dow 和 narrative 字段,它表示星期几和这一天的预报信息片段,因为这些是应用程序使用的主要字段。
  2. 要将此功能添加到您的应用程序中,可为 /forecast 路由创建一个新处理函数,向它传递数据库中的位置标识符,然后将该值的坐标插入到上面的 API 请求中。以下是相关代码:
    <?php// handler to display 7-day forecast for selected location$app->get('/forecast/{id}', function ($id) use ($app, $db) {  // look up location record in database  // connect and get forecast from Weather service  $collection = $db->locations;  $location = (array)$collection->findOne(array('_id' => new MongoId($id)));  $uri = $app->config['weather_uri'] . '/api/weather/v2/forecast/daily/10day?units=m&language=en-US&geocode=' . urlencode(sprintf('%f,%f', $location['lat'], $location['lng']));  $json = file_get_contents($uri);  if ($json === FALSE) {    throw new Exception("Could not connect to Weather API.");    }  $location['weather'] = json_decode($json, true);  return $app['twig']->render('forecast.twig', array('data' => $location));})->bind('forecast');
    Copy after login
  3. 您还可以为这个新处理函数添加一个页面模板,并从主索引页面链接到它。可以在应用程序的代码存储库中找到该模板。以下是该选项卡的示例:

第 4 步. 将您的应用程序部署到 IBM Bluemix

此刻,该应用程序已完成,您可以将它部署到 Bluemix 了。

  1. 首先,更新应用程序配置文件并修改数据库凭证,让它们指向您的远程 MongoDB 数据库部署。
  2. 然后,创建应用程序清单文件,记住通过附加一个随即字符串(比如您姓名的首字母)来使用唯一的主机和应用程序名称。
    ---applications:- name: weather-tracker-[initials]memory: 256Minstances: 1host: weather-tracker-[initials]buildpack: https://github.com/cloudfoundry/php-buildpack.gitstack: cflinuxfs2
    Copy after login
  3. CloudFoundry PHP buildpack 默认情况下不包含 PHP MongoDB 扩展,所以您必须配置该 buildpack,以便在部署期间启用该扩展。另外,如果您希望自动从 Bluemix 获取 Insights for Weather 服务凭证,那么可以更新该代码来使用 Bluemix VCAP_SERVICES 变量,如下所示:
    <?phpif ($services = getenv("VCAP_SERVICES")) {  $services_json = json_decode($services, true);  $app->config['weather_uri'] = $services_json["weatherinsights"][0]["credentials"]["url"];}
    Copy after login
  4. 您现在看可以继续将该应用程序推送到 Bluemix,然后将 Insights for Weather 服务绑定到该应用程序。
    shell> cf api https://api.ng.bluemix.netshell> cf loginshell> cf pushshell> cf bind-service weather-tracker-[initials] "Insights for Weather-[id]"shell> cf restage weather-tracker-[initials]
    Copy after login

现在可以浏览到应用程序清单中指定的主机来开始使用该应用程序,例如 http://weather-tracker- [initials] .mybluemix.net。如果看到一个空白页或其他错误,可以尝试调试您的 PHP 代码来查找出错的地方。

阅读: 在 IBM Bluemix 上调试 PHP 错误

结束语

Insights for Weather 服务使得将特定于位置的天气数据和预报添加到移动或 Web 应用程序变得很容易。因为您可以通过 REST API 访问该服务,因此可以将它与任何编程语言相集成。此外,因为该服务托管在 Bluemix 上,所以很容易将它连接到您由 Bluemix 托管的应用程序,只需将该服务绑定到您的应用程序并重新载入它。

您可以从上面的链接下载本教程中实现的所有代码,以及 PHP buildpack 的配置文件。推荐您获取该代码,使用它,并尝试添加一些新特性。我保证您不会造成任何破坏,而且它肯定对您的学习有所帮助。祝您开发愉快!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!