我们将构建一个 Amazon 店面,包含分类链接和搜索框,允许购物者浏览商店中的商品目录。与多数 PHP 应用程序不同,这个程序不需要本地数据库,因为数据库保存在 Amazon 的服务器上。所以,这个教程严重地依赖简单对象访问协议(SOAP),这个 Web 服务协议用 XML 组织信息。Web 服务是应用程序(例如在这个教程中要构建的 PHP 应用程序)与中央服务器通信以获取信息的一种方式。
通过 Amazon 电子商务服务(ECS),可以从购物者选择的分类中获得和显示内容。当选中一个分类时,将创建参数,指明这个分类,收集相关信息,并启动 SOAP 客户。SOAP 客户会接受参数,形成 XML 文档,并把 XML 文档转交给 SOAP 服务器。Amazon 服务器访问自己的数据库,生成 XML 文档,里面包含的商品与参数匹配。最后,服务器把 XML 文档返回给 SOAP 客户,SOAP 客户再把文档解析成数据结构,从数据结构中可以提取出请求的数据。
服务器为每个请求类型返回的数据都是相同的。但是,请求的设置和使用都有不同。REST 请求最简单,因为它们只是长长的 URL,URL 中包含每个商品的变量和它们的值 —— 非常像 PHP 中的 GET 请求。
另一方面,SOAP 请求更复杂,因此也就更强大。它们是通过 HTTP 传递给 SOAP 服务器的 XML 文档。SOAP 请求比 GET 请求更强大,因为它们能接受更多参数,而且多个请求也可以绑定在一个 SOAP XML 文档中,这样就支持同时请求。而且,SOAP 请求拥有优先级,这就增强了商店整体的响应性。
<?php
...
$title="Welcome to TylerCo.";
require(‘header.php‘);
...
print("
<p>Welcome to TylerCo., where you
will find great value and great service!
Guaranteed!<p> Please browse the
products on our Web site by clicking
on one of the categories to the left");
...
require(‘footer.php‘);
?>
...
require(‘header.php‘);
if($_GET[‘category‘] != ‘‘){
printCategoryItems();
}
else{
print("
<p>Welcome to TylerCo., where you will find
great value and great service!
Guaranteed!<p>
Please browse the products on our Web site by clicking
on one of the categories to the left");
}
function printPrevNextPage($totalPages, $pagenum){
$previousPage = processPrevPage();
$nextPage = processNextPage($totalPages);
print("<table width=‘100%‘><tr><td width=‘33%‘
align=‘left‘>");
print("$previousPage</td>");
print("<td width=‘33%‘ align=‘center‘>Page ".$pagenum);
print(" of $totalPages</td>");
print("<td width=‘33%‘ align=‘right‘>$nextPage
</td></tr></table>");
print("<font size=‘0‘><br><center>The
above information came from ");
print("Amazon.com. We make no guarantees to the accuracy of the above ");
print("information.</center></font>");
}
清单 26 中的函数调用两个子函数:processPrevPage() 和 processNextPage()。这个函数接受两个返回的链接,并显示它们,这样就允许客户在页面间游历。它还显示了一个免责声明,表明 Web 站点的作者对于 Amazon 提供的信息不承担责任。
...
$result = callSOAPFunction("ItemSearch", $array);
if($result->faultstring || $result->Items->Request->Errors){
error("Your search return 0 results, or perhaps there was an
error processing your request. The returned XML file with
additional error information is as follows:<br><br>",
$result->Items->Request->Errors->Error, $result);
}
else{
$items = $result->Items->Item;
if($items){
printItemsSection($innerTitle, $items);
printPrevNextPage($result->Items->TotalPages, $pagenum);
}
}
...