-1

我在做一个小的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;
}

先感谢您!

此外,API will be very limited. Mostly a path will have only one possibleREQUEST_METHOD`。

4

1 回答 1

0

如果你想让它简单易懂。那么我更喜欢以下

$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();
}
于 2017-03-07T11:37:03.580 回答