2015-10-02 31 views
1

我有一個使用JSON-RPC的Web應用程序。有一個包含這樣的代碼文件rest.php:從JSON-RPC移到簡單的RESTful API

$body = file_get_contents('php://input'); 
$jsonObj = json_decode($body); 
switch ($jsonObj->method) { 
     case 'API1': //function1 

       header($_SERVER['SERVER_PROTOCOL']." 200 OK"); 
       break; 
     case 'API2': //function2 

       header($_SERVER['SERVER_PROTOCOL']." 200 OK"); 
       break; 
     default: 
      header($_SERVER['SERVER_PROTOCOL']." 400 Bad request"); 
      break; 
    } 

開關結構根據參數「方法」調度請求。 我想改變它。我想爲每個函數創建單個REST API,每個函數都有它的URI。所以沒有參數「方法」。

有人可以給我一個提示嗎?我必須爲每個REST API創建一個文件?這是第一次在PHP中創建REST API。

非常感謝。

回答

1

有幾種方法可以實現這一點。我個人更喜歡通過URI路由發送請求[1]。如果URI路由不是一個選項,我會實現查找表來調度請求。例如,如果有以下幾種資源:

/books 
/cars 
/music 

我會根據$ _ SERVER [ 'REQUEST_URI']處理請求見[2]。例如:

$lookup_table = array(
    '/books' => function($method) { 
     switch ($method) { 
      case 'GET': { // handle GET request 

      } break; 

      case 'POST': { // handle POST request 

      } break; 
     } 
    }, 

    '/authors' => function($method) { 
     switch ($method) { 
      case 'GET': { // handle GET request 

      } break; 

      case 'PUT': { // handle PUT request 

      } break; 
     } 
    } 
); 

// this is simplification 
// REQUEST_URI needs some work before used 
$uri = $_SERVER['REQUEST_URI']; 

if (isset($lookup_table[$uri])) { 
    $lookup_table[$uri]($_SERVER['REQUEST_METHOD']); 
} 

我想這個簡單的例子會給你一些提示。

  1. http://symfony.com/doc/current/components/routing/introduction.html
  2. http://php.net/manual/en/reserved.variables.server.php