我正在尝试为我的API实现以下网址(我使用的是Codeigniter和Phil Sturgeon的REST server library):
/players -> refers to index method in the players controller
/players/rookies -> refers to rookies method in the players controller
我不希望该网址具有尾随“索引”
/players/index
当我像这样定义路线时,这完全没问题:
$route['players'] = 'players/index';
一切都按预期工作。
我的问题是我需要额外的网址段,如下所示:
/players/rookies/limit/10/offset/5/key/abcdef
以上示例有效,但以下内容不起作用:
/players/limit/10/offset/5/key/abcdef
我收到以下错误:{"status":false,"error":"Unknown method."}
显然我的控制器中没有limit
方法。
如何设置routes.php配置文件以使这些网址正常工作?
非常感谢任何帮助!
答案 0 :(得分:3)
//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
}
}
答案 1 :(得分:0)
gregory,因为你说自己“/玩家指的是玩家控制器中的索引方法”,这意味着你不应该需要$ 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 to work:
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
}