我对 REST 的一些概念有点困惑,希望能得到一些澄清。我正在关注本教程,所以我使用的任何代码都来自它。 http://phpmaster.com/rest-can-you-do-more-than-spell-it-3/
1)。每当我想发布数据时,我是否必须通过 curl 交易的整个过程?
<?php
// set up the URI value involved in a variable
$uri = "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);
2. 每当我创建一个链接时,就 URI 而言,我是否需要做一些特别的事情,或者我会根据它的访问方式来格式化它吗?
要创建指向 www.example.com/restaurant/42 的链接,我会创建以下链接,还是我需要做其他事情?
//assuming $resource = restaurant in this example
<a href ="www.example.com/".$resource."/".$id">Item 42</a>
3. 对于解析 URL 路径的代码,我是在每个文件中都有这个,还是我会创建一个文件(例如 api.php)并在每个文件中包含它?
<?php
// assume autoloader available and configured
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
$path = trim($path, "/");
@list($resource, $params) = explode("/", $path, 2);
$resource = ucfirst(strtolower($resource));
$method = strtolower($_SERVER["REQUEST_METHOD"]);
$params = !empty($params) ? explode("/", $params) : array();
if (class_exists($resource)) {
try {
$resource = new $resource($params);
$resource->{$method}();
}
catch (Exception $e) {
header("HTTP/1.1 500 Internal Server Error");
}
}
else {
header("HTTP/1.1 404 File Not Found");
}
4.我在哪里为某个类的每个功能设置可接受的“动词”?以下代码来自上面链接的教程的第 2 部分。我看到有一个类构造函数,但是我应该为那里的每个函数指定可接受的操作吗?也许我误解了这段代码,但我看不出它在哪里说 DELETE 不被接受为餐厅/id之类的东西
<?php
abstract class Resource
{
protected static $httpMethods = array("GET", "POST", "HEAD",
"PUT", "OPTIONS", "DELETE", "TRACE", "CONNECT");
protected $params;
public function __construct(array $params) {
$this->params = $params;
}
protected function allowedHttpMethods() {
$myMethods = array();
$r = new \ReflectionClass($this);
foreach ($r->getMethods(\ReflectionMethod::IS_PUBLIC) as $rm) {
$myMethods[] = strtoupper($rm->name);
}
return array_intersect(self::$httpMethods, $myMethods);
}
public function __call($method, $arguments) {
header("HTTP/1.1 405 Method Not Allowed", true, 405);
header("Allow: " . join($this->allowedHttpMethods(), ", "));
}
}