【问题标题】:Codeigniter Restful API not workingCodeigniter Restful API 不工作
【发布时间】:2014-03-10 20:29:08
【问题描述】:

我有一个安装了 Restful API 的 Codeigniter 设置。我在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-&gt;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 - 那么这里发生了什么?

【问题讨论】:

    标签: php codeigniter rest


    【解决方案1】:

    您需要加载模型。将构造函数添加到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-&gt;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
    

    【讨论】:

    • 试试$this-&gt;Artist_model-&gt;get?你得到 same 错误还是不同的错误?
    • $this-&gt;get('artist_id') 将始终为假。您没有传递 $_GET['artist_id'] 值。
    • 这还是不行……会不会是artist_id?它是 DB 表中的一列 artists
    • 怎么不行?你仍然看到同样的错误吗?你试过var_dump($artist_id) 和/或var_dump($artists) 看看里面有什么吗?
    • if($artist_id === FALSE) 之前。确保你要去/api/Allartists/artists/100
    猜你喜欢
    • 2014-02-27
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    相关资源
    最近更新 更多