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

在第 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');
  3. 接下来,更新 $APP_ROOT /views/index.twig 上的 Twig 模板以显示此信息:
    <div data-role="content">               <h2 id="Current-Weather">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>
  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');

第 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');
  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
  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"];}
  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]

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

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

结束语

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

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

Statement
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
How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)