簡體   English   中英

將RESTful URI有效地映射到API端點體系結構

[英]Efficiently Map RESTful URI to API endpoint Architecture

創建api時,每個有效的URI都會映射到一個動作。 此操作可以是特定的函數調用,也可以設置一些傳遞給泛型函數的參數。

我的問題是將URI(例如/auth/create映射到正確操作的好方法是什么?

為了說明我的嘗試:

我考慮過要命名一個與URI相同的函數,用Z替換/以直接通過其名稱調用該函數。 我基本上可以直接執行$ request_uri而不進行測試。

// from $request_uri = '/auth/create' I make;
$request_uri ='ZauthZcreate';

function ZauthZcreate($email, $password) {
  echo "i've been called as expected \n";
}
$request_uri($_GET[email],$_GET[password]);

但不適用於/user/123123類的東西。 我試圖避免陷入無盡的if-else級聯。

編輯

我對這個概念進行了迭代,找到了另一個解決方案:

$request_uri    = '/api/auth/login';
$request_path   = ltrim($request_uri,'/');
$request        = explode('/', $request_path);

// begin point for api
if($method = array_shift($request)) {
  if ($method == 'api') {
    $method($request);
  }
}

function api($request) {
  $method = __FUNCTION__.'_'.array_shift($request);
  if(is_callable($method)) {
    $method($request);
  }
}

// In a dedicated file for the scope auth

function api_auth($request) {
  $method = __FUNCTION__.'_'.array_shift($request);
  if(is_callable($method)) {
    $method($request);
  }
}

function api_auth_login($request) {
  // api end point implementation here
}
function api_auth_create($request) {
  // api end point implementation here
}

我不會使用那些Z,這將不必要地很難閱讀。 在上面的示例中,您可以僅使用AuthCreate來執行相同的操作。 您也可以通過OO設計來實現此目的,方法是為主要動詞(如Auth)創建基類,然后讓它們聲明其成員函數。

最終,您將不想使用if / else塊來解決此問題,而是解析URI的每個部分,看看是否存在正確的命名空間中的函數,並且一旦它不開始使用斜杠作為輸入(例如,上例中使用/ user的示例) / 123123)。

您也可以很好地了解其他REST API的結構,因為這是一個已解決的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM