REST,代表 REpresentational State Transfer,旨在成为普通精益化 Web 服务协议。它的出现是对 SOAP 和 XML-RPC 等重量级 Web 服务协议的响应,这些重量级的 Web 服务协议依赖于一种预定义的消息传递格式和方法在服务器和客户机之间来回传递协议。而 REST 没有规定这些限制;您可以使用任何喜欢的消息格式(无论是 JSON、XML、HTML、序列化数据还是纯文本),并使用标准的 HTTP 动词 GET、DELETE 和 POST 执行其操作。用于 REST 客户机/服务器交互的规则可以完全通过应用程序要求定义。因此,如果要定义一个打算由 JavaScript 客户机使用的 REST 接口,您也许希望数据以 JSON 格式返回;但是如果打算由 PHP 客户机来使用数据,那么序列化数据或 XML 也许是更好的选择。
每个 REST Web 服务调用只是一个简单的 HTTP 请求,使用标准的 HTTP 动词。通常,您需要使用最适合当前操作的动词:
GET用于从服务器获取数据。POST用于将数据发送到服务器。-
DELETE用于删除服务器上的资源。
清单 1 展示了一个示例如何与 Yahoo! 交互。您可以通过 PHP 搜索 REST Web 服务(参见 下载 部分获取本文使用的所有示例)。
清单 1. 在 PHP 中与 REST Web 服务交互的示例
<?php
// specify the REST web service to interact with
$url = 'http://search.yahooapis.com/WebSearchService/V1/
webSearch?appid=YahooDemo&query=sugarcrm';
// make the web services call; the results are returned in XML format
$resultsXml = file_get_contents($url);
// convert XML to a SimpleXML object
$xmlObject = simplexml_load_string($resultsXml);
// iterate over the object to get the title of each search result
foreach ( $xmlObject->Result as $result )
echo "{$result->Title}\n";
|
对于 清单 1 中的这个示例,使用 Yahoo Web Search Service 来搜索 sugarcrm。使用 PHP 函数 file_get_contents(),该函数使用指定的 URL 来执行 GET 请求。默认情况下,服务以 XML 字符串的形式返回查询结果,然后 PHP SimpleXML 库用于将该字符串解析为 PHP 对象,我们可以迭代该对象来获取正在寻找的数据。
现在您已经了解了 REST Web 服务的工作方式,下面看看如何使用 SugarCRM 的 Web 服务接口与之交互。
SugarCRM 提供一个开箱即用的 Web 服务接口,地址是:http://path_to_Sugar_instance/v2/rest.php。通过使用对该 URL 的 POST 请求来进行调用,将所需参数作为 POST 参数传递到该 Web 服务调用。对于与 Web 服务的每次交互,客户机必须使用登录方法调用来进行验证,如 清单 2 所示。
清单 2. 通过 REST Web 服务接口登录到 SugarCRM 实例
<?php
// specify the REST web service to interact with
$url = 'http://localhost/sugar/v2/rest.php';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_name' => 'user',
'password' => 'password',
);
$json = json_encode($parameters);
$postArgs = 'method=login&input_type=json&
response_type=json&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Close the connection
curl_close($session);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
// Echo out the session id
echo $result['id'];
|
由于您需要对 Web 服务发送 POST 请求而非 GET 请求,因此应使用 PHP curl 库而不是 file_get_contents() 来调用 Sugar Web 服务。然后,将用于这个 Web 服务调用的参数集合为一个数组,并将其编码为 JSON 字符串。您需要指定用于这个 Web 服务调用的参数、方法(对于这个调用是 login)以及参数格式;参数格式使用 input_type POST 参数指定,可以是 json,也可以是 serialized。您还必须使用 response_type 参数指定期望返回的结果格式,这个参数可以是 json、rss 或 serialized;然后将该 Web 服务方法使用的 JSON 编码的参数字符串指定为 rest_data。之后执行实际调用,并解码从服务器返回的 JSON 字符串。对于该请求,我们主要关心的返回值是 id 参数,这个参数将用于后续的请求中,以便已经验证的服务所在的服务器能够识别客户机。
现在可以在 清单 2 中示例的基础上构建,实际修改 Sugar Web 服务。在 清单 3 中,您将看到如何使用该接口将新记录添加到 Accounts 模块。
清单 3. 使用 REST Web 服务接口添加新帐户
<?php
// specify the REST web service to interact with
$url = 'http://localhost/sugar/v2/rest.php';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_name' => 'user',
'password' => 'password',
);
$json = json_encode($parameters);
$postArgs = 'method=login&input_type=json&
response_type=json&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Close the connection
curl_close($session);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
// Get the session id
$sessionId = $result['id'];
// Now, let's add a new Accounts record
$parameters = array(
'session' => $session,
'module' => 'Accounts',
'name_value_list' => array(
array('name' => 'name', 'value' => 'New Account'),
array('name' => 'description', 'value' => 'This is an
account created from a REST web services call'),
),
);
$json = json_encode($parameters);
$postArgs = 'method=set_entry&input_type=json&
response_type=json&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
// Get the newly created record id
$recordId = $result['id'];
|
登录到 Web 服务后,进行第二个 Web 服务调用,这次是调用 set_entry Web 服务方法。将 login 方法返回的会话 ID 指定为 session 参数,将在其中添加记录的模块指定为 module 参数。name_value_list 参数是想为新创建的记录设置的字段值的 “名称/值” 对列表。然后调用该 Web 服务,并收到新创建记录的记录 ID。
您还可以通过再次调用 set_entry 方法来更新一条记录,确保在 name_value_pair 列表中传递您想要更新的记录 ID,如 清单 4 所示。
清单 4. 使用 REST Web 服务接口创建并更新联系人
<?php
// specify the REST web service to interact with
$url = 'http://localhost/sugar/v2/rest.php';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_name' => 'user',
'password' => 'password',
);
$json = json_encode($parameters);
$postArgs = 'method=login&input_type=json&
response_type=json&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Close the connection
curl_close($session);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
// Get the session id
$sessionId = $result['id'];
// Now, let's add a new Contacts record
$parameters = array(
'session' => $session,
'module' => 'Contacts',
'name_value_list' => array(
array('name' => 'first_name', 'value' => 'John'),
array('name' => 'last_name', 'value' => 'Mertic'),
),
);
$json = json_encode($parameters);
$postArgs = 'method=set_entry&input_type=json&
response_type=json&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
// Get the newly created record id
$recordId = $result['id'];
// Now let's update that record we just created
$parameters = array(
'session' => $session,
'module' => 'Contacts',
'name_value_list' => array(
array('name' => 'id', 'value' => $recordId),
array('name' => 'title', 'value' => 'Engineer'),
),
);
$json = json_encode($parameters);
$postArgs = 'method=set_entry&input_type=json&
response_type=json&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
// Get the record id of the record we just updated
$recordId = $result['id'];
|
在这个 清单 4 示例中,仅调用第二个 set_entry 方法来更新创建的记录。这次,将要更新记录的记录 ID 指定为传递到这个 Web 服务方法调用的 name_value_list 参数中的一个条目,并将正在更新的每个字段条目作为调用的一部分(在本例中,将 title 字段值更新为 Engineer)。然后您发出请求,不出意外,这个记录 ID 将返回,这是 Web 服务方法调用成功执行的标志。
要在一个模块中创建多条记录,可以使用 Web 服务方法 set_entries 将对该 Web Services API 的调用数量减少到 1,而不是在一个循环中反复调用 set_entry,如 清单 5 所示。
清单 5. 通过一次方法调用在一个模块中创建多条记录
<?php
// specify the REST web service to interact with
$url = 'http://localhost/sugar/v2/rest.php';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_name' => 'user',
'password' => 'password',
);
$json = json_encode($parameters);
$postArgs = 'method=login&input_type=json&
response_type=json&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Close the connection
curl_close($session);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
// Get the session id
$sessionId = $result['id'];
// Now, let's add a new Contacts record
$parameters = array(
'session' => $session,
'module' => 'Contacts',
'name_value_lists' =>
array(
array('name' => 'first_name', 'value' => 'John'),
array('name' => 'last_name', 'value' => 'Mertic'),
),
array(
array('name' => 'first_name', 'value' => 'Dominic'),
array('name' => 'last_name', 'value' => 'Mertic'),
),
array(
array('name' => 'first_name', 'value' => 'Mallory'),
array('name' => 'last_name', 'value' => 'Mertic'),
),
);
$json = json_encode($parameters);
$postArgs = 'method=set_entry&input_type=json&
response_type=json&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
// Get the newly created record ids as an array
$recordIds = $result['ids'];
|
set_entries 的参数与 set_entry 基本相同,但有一个例外:这个方法不使用 name_value_list 参数,而是使用 name_value_lists 参数,这个参数是使用 Web Services API 创建的多条记录的一个关联数组。已创建记录的记录 ID 在 ids 参数中作为数组返回,数组中记录 ID 的顺序与在参数列表中传送它们的顺序相同。
SugarCRM 的一个主要特性是能够使记录相互关联。这种关系的一个示例是 Account 和 Contact 之间的关系:SugarCRM 中的每个 Account 可以与一个或多个 Contact 关联。可以使用 Web 服务框架来完整地构建这种关系,如 清单 6 所示。
清单 6. 使用 REST Web Services API 关联 Account 和 Contact
<?php
// specify the REST web service to interact with
$url = 'http://localhost/sugar/v2/rest.php';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array(
'user_name' => 'user',
'password' => 'password',
);
$json = json_encode($parameters);
$postArgs = 'method=login&input_type=json&
response_type=json&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Close the connection
curl_close($session);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
// Get the session id
$sessionId = $result['id'];
// Now, let's add a new Accounts record
$parameters = array(
'session' => $session,
'module' => 'Accounts',
'name_value_list' => array(
array('name' => 'name', 'value' => 'New Account'),
array('name' => 'description', 'value' => 'This is an
account created from a REST web services call'),
),
);
$json = json_encode($parameters);
$postArgs = 'method=set_entry&input_type=json&
response_type=json&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
// Get the newly created Account record id
$accountId = $result['id'];
// Now, let's add a new Contacts record
$parameters = array(
'session' => $session,
'module' => 'Contacts',
'name_value_list' => array(
array('name' => 'first_name', 'value' => 'John'),
array('name' => 'last_name', 'value' => 'Mertic'),
),
);
$json = json_encode($parameters);
$postArgs = 'method=set_entry&input_type=json&
response_type=json&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($session);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
// Get the newly created Contact record id
$contactId = $result['id'];
// Now let's relate the records together
$parameters = array(
'session' => $session,
'module_id' => $accountId
'module_name' => 'Accounts',
'link_field_name' => 'contacts',
'related_ids' => array($contactId),
);
$json = json_encode($parameters);
$postArgs = 'method=set_relationship&input_type=json&
response_type=json&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call
$response = curl_exec($session);
|
创建需要关联的 Account 和 Contact 之后,构建请求调用 set_relationship Web 服务方法。然后,传递以下参数:
-
session参数,用于获取 Web 服务会话的会话 ID。 module_name参数,用于获取关系的主模块。module_id参数,用于获取将作为关系基础的模块中的记录 ID。link_field_name参数,用于获取模块中用于链接到其他模块的关系的名称(在本例中,关系名为contacts)。
最后,指定一个记录 ID 列表,这个列表将关联到指定的模块记录。执行调用后,这种关系就会建立。
这只是大量可用 Web 服务方法的冰山一角;您可以查阅 SugarCRM Developer Documentation,了解可用 Web 服务方法的完整列表。
在本文中,我们了解了 SugarCRM 5.5 中的一个新特性,即 Sugar Web 服务框架的 REST 接口。首先了解了 REST Web 服务的工作方式,然后,查看了几个运用 Sugar Web 服务框架 REST 接口的示例。我们学习了如何向模块添加新记录,以及如何修改该记录。还学习了如何通过一个方法调用添加多条记录,避免了连续执行多个远程服务器调用的开销。最后,我们了解了如何使用 Web 服务框架的 set_relationship 方法来关联两个不同的记录。
| 描述 | 名字 | 大小 | 下载方法 |
|---|---|---|---|
| 文章示例 | rest.php.samples.zip | 5KB | HTTP |
学习
-
Sugar Developer Documentation:参阅各种 SugarCRM API 的详细指南。
-
Sugar Developer Zone:找到面向所有 SugarCRM 开发人员的资源。
- The Definitive Guide to SugarCRM: Better Business Applications:参阅基于 SugarCRM 开发应用程序的优秀指南。
- 构建 RESTful Web 服务(Andrew Glover,developerWorks,2008 年 7 月):在该教程中,详细了解 REST 的基本概念,并使用 Restlets 逐步构建应用程序。
- 学习 PHP 系列:通过 developerWorks 上的这些教程,学习如何使用 PHP 编程。
- PHP.net:参阅 PHP 文档,将这个通用的脚本语言应用于 Web 开发和 HTML。
- 推荐 PHP 读物列表:参阅这个由 IBM Web 应用程序开发人员编辑的、面向程序员和管理员的 PHP 阅读列表。
- PHP 内容:在 developerWorks 上浏览与 PHP 相关的文章、教程等。
- IBM developerWorks 上的 PHP 项目资源:扩展您的 PHP 技能。
- XML 1.0 Specification(W3C Recommendation,2008 年 11 月 26 日):参阅该资源,了解 CDATA 区域等 XML 特性的具体细节。
- The XML FAQ:探索 XML 信息的另一个优秀资源 —— Peter Flynn 编辑的 XML FAQ。
- 来自 W3schools.com 的 XML DOM 教程:了解浏览器可用的基于 XML 的界面(以及支持这些界面的浏览器)。
- XHTML™ 1.0: The Extensible HyperText Markup Language(World Wide Web Consortium Recommendation,2000 年 1 月 26 日):阅读关于 XHTML 1.0 的更多信息。XHTML 1.0 是一个 XML 1.0 应用程序、HTML 4 的全新版本,为未来的 XHTML 扩展性奠定了基础。
- developerWorks XML 专区:在 XML 专区获取提高您的专业技能所需的资源。
-
访问 developerWorks Open source 专区,获得丰富的 how-to 信息、工具和项目更新,帮助您用开放源码技术进行开发,并与 IBM 产品结合使用。
- IBM XML 认证:了解如何才能成为一名 IBM 认证的 XML 和相关技术的开发人员。
- XML 技术库:访问 developerWorks XML 专区,获得广泛的技术文章和技巧、教程、标准和 IBM 红皮书。
- developerWorks 技术活动 和 网络广播:随时关注这些活动中的技术。
- developerWorks
播客:收听面向软件开发人员的有趣访谈和讨论。
获得产品和技术
- 下载 IBM 产品评估试用版软件
或 IBM SOA Sandbox for Reuse,并开始使用来自 DB2®、Lotus®、Rational®、Tivoli® 和
WebSphere® 的应用程序开发工具和中间件产品。
讨论
- XML
专区讨论论坛:参与任何一个 XML 相关讨论。
- developerWorks 博客:阅读这些博客并参与讨论。
John Mertic 是 SugarCRM 公司的一位软件工程师,拥有数年 PHP Web 应用程序经验。在 SugarCRM,他专攻数据集成、移动和用户界面架构。作为一位热心的作者,他已在 php|architect、IBM developerWorks 和 Apple Developer Connector 中发表了多篇文章,他还是 “The Definitive Guide to SugarCRM: Better Business Applications” 一书的作者。他曾经为很多开源项目做出过贡献,最著名的是 PHP 项目;在该项目中,他是 PHP Windows Installer 的创建者和维护者。