在CodeIgniter中使用REST API时如何定义函数?

时间:2018-09-19 21:51:39

标签: php json rest api codeigniter

我创建了一个名为Api.php的控制器,然后扩展了Rest_Controller。我注意到在此控制器中创建函数时只能使用index_get()

<?php

class Api extends REST_Controller{

    public function __construct()
    {
        parent::__construct();

    }

    public function index_get(){
        $car_id = $this->get('car_id');
        if(!$car_id){

            $this->response("No Car ID specified", 400);

            exit;
        }

        $result = $this->model_getvalues->getCars( $car_id );

        if($result){

            $this->response($result, 200); 

            exit;
        } 
        else{

             $this->response("Invalid Car ID", 404);

            exit;
        }
    }

}

但是当我尝试创建所需的函数(例如 getAllCars())而不是 index_get()时,我收到一条错误消息,告诉我未知函数。

在CodeIgniter中使用rest api库时,如何定义自己的函数而不使用 index_get()

2 个答案:

答案 0 :(得分:0)

默认情况下,https://github.com/chriskacerguis/codeigniter-restserver#handling-requests的方法是index_get(),另一种使用您自己的方法的方法是使用HTTP GET参数进行播放 例如:

if($this->get('car_id') == 'all'){
  //your own function here
}

或者,如果您真的想创建自己的方法,则可以参考此http://programmerblog.net/create-restful-web-services-in-codeigniter/

答案 1 :(得分:0)

感谢我已经弄清楚了,我才发现_get之前的名称对URL很重要,即,当具有类似getCars_get的方法时,您将只能使用不带_get的getCars来调用它依附它,对我有用。这意味着在API控制器中可以有多个_get方法。