CodeIgniter Restserver不适用于特定的URL

时间:2013-01-30 15:43:32

标签: php codeigniter rest

我将此Restserver与CodeIgniter结合使用。

除非我像这样使用URL,否则似乎工作得很好; mydomain.com/api/example/1234 /

其中1234是我要求的ID。

这样的代码似乎不起作用:

class Example extends REST_Controller {
    public function index_get() {
        print($this->get("example"));
    }
}

它是GET还是POST请求似乎并不重要。必须有一种方法可以从URL中检索ID ..

2 个答案:

答案 0 :(得分:0)

网址的细分应与以下内容相同:

api = Controller
example = Resource

参数必须是键值对:

id = Key
1234 = Value

似乎你的1234被作为一把钥匙,但没有任何价值。尝试将您的网址更改为以下内容:mydomain.com/api/example/id/1234/,该网址会转换为:mydomain.com/controller/resource/key/value/

这里还有一个非常详细的教程:http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/

修改 由于您的控制器位于子文件夹中,因此您的网址段应按如下方式构建:

api/example = Controller
user = Resource // basically the method name + the http method e.g. user_get(), or user_post(). I just made 'user' up, for your app can be whatever it is that people will access via your api

参数必须作为键值对提供:

id = Key
1234 = Value

那么您的网址将如下所示:mydomain.com/api/example/user/id/1234/

答案 1 :(得分:0)

对于GET REQUEST,您只需在函数的标题中定义参数,如下所示:

public function index_get($param) {
    print($param);
}

如果要使其可选,则:

public function index_get($param="") {
    if ($param=="") {
       print("No Parameters!");
    } else {
       print($param);
    }
}

如果我想发送“ POST”参数,我只需创建一个POST方法并按原样接收它们...

public function index_post() {
$params = $this->post();
if (isset($param['id'])) {
   print($param['id']);
} else {
   print("No Parameters!");
}

}