休息API:先做什么,区分REQUEST_METHOD还是PATH_INFO?
Rest API: What do first, distinguish REQUEST_METHOD or PATH_INFO?
我正在做一个小的REST API
,写在PHP
。
是否有最佳实践来决定脚本应该做什么?
我是先检查请求是 GET
、POST
、PUT
、DELETE
还是先检查 PATH_INFO
.
示例首先检查 PATH_INFO
:
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'))[0];
switch ($request)
{
case 'books':
if ($method = 'GET')
{
getbooks();
} elseif ($method = 'POST')
{
postbooks();
}
break;
default:
include_once('error.php');
break;
}
示例先检查REQUEST_METHOD:
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'))[0];
switch ($method)
{
case 'GET':
if ($request = 'books')
{
getbooks();
} elseif ($request = 'user')
{
getuser();
}
break;
default:
include_once('error.php');
break;
}
提前致谢!
此外,APIwill be very limited. Mostly a path will have only one possible
REQUEST_METHOD`。
如果你想让它简单易懂。那么我更喜欢以下
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'))[0];
if($method == "GET" && $request == "books"){
getBooks();
}elseif ($method == "POST" && $request == "books"){
addBooks();
}elseif ($method == "PUT" && $request == "books"){
updateBooks();
}elseif ($method == "DELETE" && $request == "books"){
deleteBooks();
}
我正在做一个小的REST API
,写在PHP
。
是否有最佳实践来决定脚本应该做什么?
我是先检查请求是 GET
、POST
、PUT
、DELETE
还是先检查 PATH_INFO
.
示例首先检查 PATH_INFO
:
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'))[0];
switch ($request)
{
case 'books':
if ($method = 'GET')
{
getbooks();
} elseif ($method = 'POST')
{
postbooks();
}
break;
default:
include_once('error.php');
break;
}
示例先检查REQUEST_METHOD:
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'))[0];
switch ($method)
{
case 'GET':
if ($request = 'books')
{
getbooks();
} elseif ($request = 'user')
{
getuser();
}
break;
default:
include_once('error.php');
break;
}
提前致谢!
此外,APIwill be very limited. Mostly a path will have only one possible
REQUEST_METHOD`。
如果你想让它简单易懂。那么我更喜欢以下
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'))[0];
if($method == "GET" && $request == "books"){
getBooks();
}elseif ($method == "POST" && $request == "books"){
addBooks();
}elseif ($method == "PUT" && $request == "books"){
updateBooks();
}elseif ($method == "DELETE" && $request == "books"){
deleteBooks();
}