Part 1 of this series dealt with REST from a theoretical perspective, specifically, what the heck is it. And then, part 2 dove deeper, talking about how you might go about building a REST-oriented system. It’s certainly been an exciting journey of self-realization thus far, but there’s no time to rest, if you will. We must keep going!
本系列的第1部分从理论角度探讨了REST,特别是它到底是什么。 然后, 第2部分深入探讨了如何构建面向REST的系统。 到目前为止,这当然是一个令人兴奋的自我实现之旅,但是如果您愿意的话,没有时间休息。 我们必须继续前进!
Imagine it’s a warm, sunny, summer day. You’re just walking along, taking a leisurely noonday stroll, when all of a sudden you come face to face with a RESTful API. What do you do? How do you interface with it? Or, as those of us in the know would say, “how do you consume RESTful services?” That, my friends, is the subject of this article.
想象这是一个温暖,阳光明媚的夏日。 当您突然与RESTful API面对面时,您只是在走来走去,悠闲地中午漫步。 你是做什么? 您如何与之交互? 或者,正如我们中的知情人士所说:“您如何使用RESTful服务?” 我的朋友们,这就是本文的主题。
There are essentially three basic things that need to be done within your PHP program to consume REST services over HTTP: specifying the URL for the resource to be accessed (either used or created), specifying any parameters needed to accompany the request, and finally invoking the correct HTTP verb to do the actual retrieving or updating/creating.
要在HTTP上使用REST服务,PHP程序中本质上需要完成三件事:指定要访问(使用或创建)的资源的URL,指定请求所需要的任何参数,最后调用正确的HTTP动词来进行实际的检索或更新/创建。
First, you need to determine the URL that you want to create, get, update, or delete. Remember, every REST resource is identified by a unique URL, so that choosing the correct URL to use is very important. Sometimes the pieces that make up the URL will be strictly defined by the API, and other times the API will accept anything, no matter how long or obtuse. In such cases where you define the URL yourself, you should make an effort to make it as short and yet meaningful as possible. URLs should be human readable.
首先,您需要确定要创建,获取,更新或删除的URL。 请记住,每个REST资源都由唯一的URL标识,因此选择正确的URL使用非常重要。 有时,组成URL的部分将由API严格定义,而有时,API将接受任何内容,无论时间长短或钝。 在这种情况下,您自己定义URL,则应努力使其尽可能简短而有意义。 URL应该是人类可读的。
Second, you need to think about the data that you will use in the transaction. That is, any web interaction is going to involve moving data to or from applications and so setting up the data that you are going to transfer is pretty important. There are a number of ways in which this can be done; you could provide the data as GET or POST parameters, HTTP headers, or even an XML or JSON payload.
其次,您需要考虑将在事务中使用的数据。 也就是说,任何Web交互都将涉及在应用程序之间移动数据,因此设置要传输的数据非常重要。 有很多方法可以做到这一点。 您可以将数据提供为GET或POST参数,HTTP标头,甚至XML或JSON负载。
And now, the final step; talking to the REST service. As you might guess, there are a number of ways to do this. If you are using a framework like Zend Framework or WS02 then you’ll most likely have REST/HTTP convenience functions made available to you by it. If you are not using a framework, then there are two PHP extensions in particular you’ll find helpful. The first (and the one I’ll use here) is cURL, a wrapper around the libcurl library. The second is the pecl_http extension, which can easily be downloaded and installed via PECL. Either one should work nicely for you, allowing you to write PHP code that can easily work with HTTP content and headers.
现在,最后一步; 与REST服务对话。 您可能会猜到,有很多方法可以做到这一点。 如果您使用的是Zend Framework或WS02之类的框架 ,那么您很可能会使用REST / HTTP便利功能。 如果您不使用框架,那么会有两个PHP扩展特别有用。 第一个(也是我将在此处使用的那个)是cURL,它是libcurl库的包装器。 第二个是pecl_http扩展名,可以通过PECL轻松下载和安装。 任一种都适合您,让您编写可以轻松使用HTTP内容和标头PHP代码。
I should probably also mention that that you don’t need to use cURL or PECL; of course you can do everything with straight-up PHP function (like fopen() and file_put_contents()), but it’s a bit more wordy and not quite as elegant. For an example of using such PHP functions to communicate with remote a remote server, see Dustin Runnell’s article Understanding OAuth – Tweeting from Scratch.
我可能还应该提到,您不需要使用cURL或PECL。 当然,您可以使用简单PHP函数(例如fopen()和file_put_contents() )来完成所有操作,但是它比较罗word,不够优雅。 有关使用此类PHP函数与远程服务器进行远程通信的示例,请参见Dustin Runnell的文章“ 理解OAuth –从头开始推文” 。
There are four steps to every cURL activity:
每个cURL活动有四个步骤:
Initialize a cURL resource 初始化cURL资源 Set any necessary cURL options 设置任何必要的cURL选项 Execute the HTTP call 执行HTTP调用 Parse the returned response 解析返回的响应So without further ado, let’s bring the three main steps (and 4 curl-specific steps) together with an example:
因此,事不宜迟,让我们将三个主要步骤(和4个特定于curl的步骤)与一个示例结合在一起:
<?php // set up the URL value involved in a variable $url = "http://www.funland.com/summerschedule"; // set up the data that is going to be passed $events = array( array("event" => "20120601-0001", "name" => "AC/DC Drink Till U Drop Concert", "date" => "20120601", "time" => "22000030"), array("event" => "20120602-0001", "name" => "Enya – Can You Feel the Peace", "date" => "20120602", "time" => "19300045"), array("event" => "20120603-0002", "name" => "Nicki Menaj – The Midnight Girls Concerrtt", "date" => "20120603", "time" => "21300039")); $jsonData = json_encode($events) // perform the curl transaction $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData); $response = curl_exec($ch); $decode = json_decode($response); print_r($resonse);The example specifies the target resource that will be called, and a JSON payload with event information. Then a cURL handle is initialized using the curl_init() function. The handle is used with subsequent cURL functions related to this call.
该示例指定了将被调用的目标资源以及带有事件信息的JSON有效负载。 然后,使用curl_init()函数初始化cURL句柄。 该句柄与与此调用相关的后续cURL函数一起使用。
Then a few cURL options are set to tell cURL what it is exactly that you want it to do. This is done through the curl_setopt() function.
然后设置了一些cURL选项,以告诉cURL您想要它做什么。 这是通过curl_setopt()函数完成的。
CURLOPT_URL – lets cURL know the URL you want to operate on, in this case using the $url variable that was defined previously.
CURLOPT_URL –在这种情况下,使用先前定义的$url变量,使cURL知道要操作的URL。
CURLOPT_RETURNTRANSFER – tells cURL not to send the response directly to browser but to return it as a string from curl_exec() instead.
CURLOPT_RETURNTRANSFER –告诉cURL不要将响应直接发送到浏览器,而是从curl_exec()作为字符串返回。
CURLOPT_POST – identifies what HTTP verb to use, in this case POST. Note that the value true is required as the third parameter here or else the statement will not work.
CURLOPT_POST –标识要使用的HTTP动词,在本例中为POST 。 请注意,此处必须将值true作为第三个参数,否则该语句将不起作用。
cURL is a very flexible library and there is a plethora of configurable options you can specify. For a complete list, be sure to check out the cURL documentation on the PHP site.
cURL是一个非常灵活的库,您可以指定很多可配置选项。 有关完整列表,请确保查看PHP网站上的cURL文档 。
Then it’s time to actually execute the cURL call and interpret the results. As written above, the data that is entered into JSON via the json_encode() function will be passed on to cURL using the $jsonData variable. If you were doing a GET, then the logic would be similar except CURLOPT_GET would be used and you would follow up the cURL commands with the json_decode() function that would take the JSON data returned and move it into a PHP array.
然后是时候实际执行cURL调用并解释结果了。 如上所述,通过json_encode()函数输入JSON的数据将使用$jsonData变量传递到cURL。 如果您正在执行GET ,则逻辑将类似,除了将使用CURLOPT_GET ,并且您将使用json_decode()函数跟踪cURL命令,该函数将获取返回的JSON数据并将其移入PHP数组。
This article presented a very simple outline of how to do an HTTP connection from your PHP scripts. Now the only remaining question is – how does this model qualify as RESTful and how do you keep it that way? Keep in mind that since REST is a state of mind, rather than a standard, there can be a certain amount of debate as to whether a specific system is RESTful or not. But let’s go back to our basic principles.
本文简要介绍了如何通过PHP脚本建立HTTP连接。 现在剩下的唯一问题是–该模型如何符合RESTful的标准,如何保持这种状态? 请记住,由于REST是一种心态,而不是一种标准,因此对于特定系统是否使用RESTful可能存在一定的争论。 但是,让我们回到我们的基本原则。
REST treats everything as a resource and assigns a URL to that resource. And we got to do that with the first line of code. The URL in addition forms a meaningful name, is in direct opposition to an RPC architecture where everything goes to an action node and not necessarily the final destination.
REST将所有内容都视为资源,并为该资源分配一个URL。 我们必须使用第一行代码来做到这一点。 URL还形成了一个有意义的名称,它与RPC体系结构直接相反,在RPC体系结构中,所有内容都传递给操作节点,而不一定是最终目的地。
REST is stateless, and as noted from the example, there is nothing in there that carries information about previous or future transactions. Each one is independent of what happened before (except for normal data dependencies).
REST是无状态的,并且从示例中可以看出,其中没有任何内容可以承载有关先前或将来的事务的信息。 每一个都独立于之前发生的事情(正常数据依赖关系除外)。
REST is about simplicity, and yet is robust and powerful. The example used a standard protocol (HTTP) and the cURL extension. Nothing special needs to be loaded, just the basic capabilities of PHP and HTTP.
REST是关于简单性的,但功能强大而强大。 该示例使用标准协议(HTTP)和cURL扩展名。 不需要加载任何特殊内容,只需加载PHP和HTTP的基本功能即可。
And speaking of HTTP, there is one more thing that needs to be explored; something that we hinted about with the print_r() statement above; response codes and HTTP headers. If you are going to do a POST or other operations that are carried out on the server, then you need to have some idea as to whether or not it worked. Similarly, you may also want to give the server some directions on how to do the POST or what type of data to pick up with a GET. All of this and more (well, mostly “all of this”) will be covered in the final chapter of the saga where I’ll introduce you to the fascinating world of HTTP headers.
说到HTTP,还需要探索一件事。 我们在上面的print_r()语句中暗示过的东西; 响应代码和HTTP标头。 如果要执行POST或在服务器上执行的其他操作,则需要对它是否起作用有所了解。 同样,您可能还希望为服务器提供一些指导,说明如何进行POST或使用GET提取哪种类型的数据。 所有这些以及更多(嗯,主要是“所有这些”)将在传奇的最后一章中介绍 ,在这里我将向您介绍迷人的HTTP头世界。
Image via littlesam / Shutterstock
图片来自littlesam / Shutterstock
翻译自: https://www.sitepoint.com/rest-can-you-do-more-than-spell-it-3/
相关资源:jdk-8u281-windows-x64.exe