PHP Restler 支持包含在其他 URL 中的 API URL



..想不出一个足够描述性的标题。 我要问的是我该怎么做?

我想要以下 2 个 API 调用

 GET /api/users/2/duels - returns all of the duels for user 2 
 GET /api/users/2 - returns the profile for user 2

由于 PHP 不支持方法重载,因此我不清楚如何使其工作。

目前我有功能

 function get($id, $action){
      //returns data based on action and id
 }

而且我不能只做

 function get($id){
      //returns profile based on id
 } 

因为上述原因。

任何帮助将不胜感激!!

您可以使用

phpdoc 装饰器@url告诉 restler 任何与直接类>方法映射不匹配的特殊调用方案。

/**
 * @url GET /api/users/:userId/duels
 */
public function getDuels($userId)
{
}
.

.应该可能工作。

一种方法是使用条件块在同一函数中处理这两种情况,如下所示

function get($id, $action=null){
    if(is_null($action)){
        //handle it as just $id case
    }else{
        //handle it as $id and $action case
    }
}

如果您运行的是 restler 3 及更高版本,则必须禁用智能路由

/**
* @smart-auto-routing false
*/
function get($id, $action=null){
    if(is_null($action)){
        //handle it as just $id case
    }else{
        //handle it as $id and $action case
    }
}

另一种方法是拥有多个函数,因为 index 也映射到 root,您几乎没有选择,您可以将函数命名为 get、index、getIndex

function get($id, $action){
    //returns data based on action and id
}
function index($id){
    //returns profile based on id
}

如果您使用的是 Restler 2 或关闭smart routing,则函数的顺序对于消除歧义很重要

如果函数名称的选项用完了,则可以按照@fiskfisk建议使用@url映射,但路由应仅包含方法级别,因为类路由始终在前面,除非您使用 $r->addAPIClass('MyClass',''); 将其关闭

function get($id){
    //returns data based on action and id
}
/**
 * @url GET :id/duels
 */
function duels($id)
{
}

最新更新