我有一个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
- 错误...当我输入http://localhost/myprojects/ci/index.php/api/Allartists/artists/artist_id/100
时,我收到PHP错误Undefined property: Allartists::$artist_model
- 那么这里发生了什么?
答案 0 :(得分:0)
您需要加载模型。将构造函数添加到Allartists
并加载它。
class Allartists extends REST_Controller{
function __construct(){
parent::__construct();
$this->load->model('Artist_model');
}
// ...
}
P.S。您的模型需要将其类名中的第一个字母大写(请参阅:http://ellislab.com/codeigniter/user-guide/general/models.html):
class Artist_model extends CI_Model{
// ...
}
更新:您正在寻找$this->get('artist_id')
。由于您未在网址中发送$_GET['artist_id']
值(?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
或,保留当前代码,您只需将网址更改为:
即可http://localhost/myprojects/ci/index.php/api/Allartists/artists?artist_id=100