[英]Codeigniter RESTful API - How to get parameters
I have this model in my Codeigniter setup: 我的Codeigniter设置中有以下模型:
function get_all_artists(){
$this->db->select('artist_id, artist_name');
$this->db->from('artists');
return $this->db->get();
}
How do I fetch those parameters in my Rest_Controller setup? 如何在Rest_Controller设置中获取这些参数? How would the
_get()
-function look like? _get()
函数的外观如何?
public function artists_get()
{
???
}
Thanks in advance 提前致谢
Try 尝试
public function artists_get(){
$this->load->model('your_model_name');// load model here
$res = $this->your_model_name->get_all_artists();
$result = $res->result_array();// get result as associative array
return json_encode($result);// encode with json
}
With this library you need to append the method type to the function name. 使用此库,您需要将方法类型附加到函数名称中。
_get
for GET
, _post
for POST
, _put
for PUT
, _delete
for DELETE
. _get
表示GET
, _post
表示POST
, _put
表示PUT
, _delete
表示DELETE
。 eg functionname_get()
. 例如
functionname_get()
。
As noted in another answer you'll want to retrieve results as an array. 如另一个答案中所述,您将希望以数组形式检索结果。 So
$this->db->get()->result_array();
所以
$this->db->get()->result_array();
To retrieve data from the model: 要从模型检索数据:
$this->load->model('model_name');
$artists = $this->model_name->get_all_artists();
If you want to send json to front end then you need to do something like this: 如果您想将json发送到前端,则需要执行以下操作:
$vars['artists'] = json_encode($artists);
$this->_getTemplate('default')->build('artists_page', $vars);
If you are using the REST EXTENSION for CodeIgniter then you must create an object and invoke the method "Respose". 如果将REST EXTENSION用于CodeIgniter,则必须创建一个对象并调用方法“ Respose”。
public function artists_get() {
$response = array(
'status'=>TRUE,
'data'=>$result, // This can be an object or array
'obs'=>'all',
);
$this->response($response);
}
That's the official way to do it... and it works perfectly! 这是执行此操作的官方方法……而且效果很好!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.