4

我正在尝试为我的 API 实现以下 URL(我正在使用 Codeigniter 和 Phil Sturgeon 的REST 服务器库):

/players            -> refers to index method in the players controller
/players/rookies    -> refers to rookies method in the players controller

我不希望 URL 有一个尾随的“索引”

/players/index

当我像这样定义路由时,这根本没有问题:

$route['players'] = 'players/index';

一切都按预期工作。

我的问题是我需要额外的 URL 段,如下所示:

/players/rookies/limit/10/offset/5/key/abcdef

上面的示例有效,但以下示例无效:

/players/limit/10/offset/5/key/abcdef

我收到以下错误:{"status":false,"error":"Unknown method."} 显然我的控制器中没有limit方法。

如何设置我的 routes.php 配置文件以使这些 URL 正常工作?

任何帮助深表感谢!

4

2 回答 2

4
//www.mysite.com/players
$route['players'] = 'players/index_get';//initial call to players index

//www.mysite.com/players/rookies
/** overrides the above **/
$route['players/(:any)'] = 'players/index_get/$1';//Changing defaults index

//www.mysite.com/players/rookies/10/4
/** overrides the above **/
$route['players/(:any)/(:num)/(:num)'] = 'players/index_get/$1/$2/$3';//Changing type,limit,offset

//All routes that are similar, like above that follow the previous, override the preceding one. 


//www.mysite.com/players/create
//overrides $route['players/(:any)']
$route['players/create'] = 'players/index_post';


class Players extends REST_Controller
{
    public $player_types = array();

    public function __construct(){
       $this->player_types = array(
          'rookies', 'seniors'
       );//manual assign or pull from db
    }
    /**
     * Index
     * $_GET
    **/
    public function index_get($type='rookies',$offset=0, $limit=0)//some defaults to show on initial call
    {
        // www.mysite.com/players/rookies
        // $route['players/(:any)'] = 'players/index_get/$1';
        // First uri segment, check to see if its a valid player 'type'

        if(!in_array(strtolower($type), $this->player_types)){
             //redirect ?
             return;
        }
    }
    /**
     * Index
     * $_POST
    **/
    public function index_post()
    {
        // Create a new player
    }
}
于 2013-02-05T18:59:02.633 回答
0

gregory,正如你所说的“/players 指的是玩家控制器中的索引方法”,这意味着如果你的路由是干净的,你不需要有 $route['players'] = 'players/index' 。

您可以拥有任意数量的段,并获取 URI 类以在脚本中区分它们。这意味着这个 URL “/players/rookies/limit/10/offset/5/key/abcdef” 默认应该指向你的玩家控制器,rookies() 方法。以下是获取细分的方法:

function rookies () {
    //$this->uri->segment (1); would return 'players' or 'limit'
    //$this->uri->segment (8); would return 'abcdef' or false
}

除了 /players/limit 工作:

function limit () {
    $this->rookies();
}

编辑 1

这是另一种方法:

路由规则:

$route['/players/rookies/limit/(:num)/offset/(:num)/key/(:any)'] = "players/get"
$route['/players/limit/(:num)/offset/(:num)/key/(:any)'] = "players/get"

在控制器中

function get () {
    //work with segments
}
于 2013-02-05T16:42:50.987 回答