我有一个Codeigniter设置,我安装了Restful API的东西。我在application->controller->api
中创建了一个API文件夹,之后我创建了一个API,看起来像这样:
<?php
require(APPPATH.'libraries/REST_Controller.php');
class Allartists extends REST_Controller{
function artists_get()
{
if(!$this->get('artist_id'))
{
$this->response(NULL, 400);
}
$artists = $this->artist_model->get( $this->get('artist_id') );
if($artists)
{
$this->response($artists, 200);
}
else
{
$this->response(array('error' => 'Couldn''t find any artists!'), 404);
}
}
?>
在我的application->models
-文件夹中,我有文件artist_model.php
,看起来像这样:
<?php
Class artist_model extends CI_Model
{
function get_all_artists(){
$this->db->select('*');
$this->db->from('artists');
return $this->db->get();
}
}
?>
所以,当我输入http://localhost/myprojects/ci/index.php/api/Allartists/artists/
时,我得到400 - Bad Request
-error…当我输入http://localhost/myprojects/ci/index.php/api/Allartists/artists/artist_id/100
时,我得到PHP错误Undefined property: Allartists::$artist_model
-那么这里发生了什么?
您需要加载您的模型。为Allartists
添加一个构造函数并加载它
class Allartists extends REST_Controller{
function __construct(){
parent::__construct();
$this->load->model('Artist_model');
}
// ...
}
注:您的模型需要将类名中的第一个字母大写(参见:http://ellislab.com/codeigniter/user-guide/general/models.html):
)。class Artist_model extends CI_Model{
// ...
}
更新:您正在寻找$this->get('artist_id')
。这将永远不会被设置,因为您没有发送$_GET['artist_id']
值(URL中的?artist_id=100
)。您需要在控制器中以另一种方式获取$artist_id
。
function artists_get($artist_id=FALSE)
{
if($artist_id === FALSE)
{
$this->response(NULL, 400);
}
$artists = $this->artist_model->get( $artist_id );
if($artists)
{
$this->response($artists, 200);
}
else
{
$this->response(array('error' => 'Couldn''t find any artists!'), 404);
}
}
然后转到:
http://localhost/myprojects/ci/index.php/api/Allartists/artists/100
或,保持当前代码,您可以简单地将URL更改为:
http://localhost/myprojects/ci/index.php/api/Allartists/artists?artist_id=100