有效地将RESTful URI映射到API端点架构

时间:2015-10-24 21:20:35

标签: php rest

创建api时,每个有效的URI都映射到一个动作。此操作可以是特定的函数调用,也可以设置传递给泛型函数的一些参数。

我的问题是将/auth/create等uri映射到正确的行动的方法是什么或者什么是好的。

说明我的尝试:

我考虑过将命名命名为将/替换为Z的URI,以便通过名称直接调用该函数。我基本上可以直接执行$ 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
}

1 个答案:

答案 0 :(得分:0)

我不会使用那些Z,这将是不必要的难以阅读。在上面的例子中,你可以用AuthCreate做同样的事情。您也可以通过为主要动词(如Auth)创建基类,然后让它们声明其成员函数来完成OO设计。

最终你不想用if / else块来解决这个问题,而是解析URI的每个部分,看看右边命名空间中的函数是否存在,并且一旦它没有开始使用斜杠作为输入(对于上面的例子) with / user / 123123)。

看看其他REST API是如何构建的,你也可以做得很好,因为这是一个已经解决的问题

相关问题