构建REST API代码Igniter

时间:2015-06-01 23:34:47

标签: php codeigniter rest

我正在尝试为我的网站开发REST API。我正在使用CodeIgniter的PHP框架。我已按照http://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter-2--net-8814中提到的教程创建了restful apis。本教程基于https://github.com/chriskacerguis/codeigniter-restserver

上开发的代码

我已将rest.php放在application / config文件夹中,将REST_Controller.php放在application / libraries /

我在application / controllers / example.php中创建了一个api

require APPPATH.'/libraries/REST_Controller.php';

    class example extends REST_Controller
    {
        function __construct()
        {
            // Construct our parent class
            parent::__construct();
        }
       function user_get()
        {
            if(!$this->get('id'))
            {
                $this->response(NULL, 400);
            }
            // $user = $this->some_model->getSomething( $this->get('id') );
            $users = array(
                1 => array('id' => 1, 'name' => 'Some Guy', 'email' => 'example1@example.com', 'fact' => 'Loves swimming'),
                2 => array('id' => 2, 'name' => 'Person Face', 'email' => 'example2@example.com', 'fact' => 'Has a huge face'),
                3 => array('id' => 3, 'name' => 'Scotty', 'email' => 'example3@example.com', 'fact' => 'Is a Scott!', array('hobbies' => array('fartings', 'bikes'))),
            );

            $user = @$users[$this->get('id')];

            if($user)
            {
                $this->response($user, 200); // 200 being the HTTP response code
            }
            else
            {
                $this->response(array('error' => 'User could not be found'), 404);
            }
        }
    }

我有一个.htaccess文件,如下所示:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

但是当我向mywebsite.com/index.php/example/id/1发送GET请求时,它会重定向到主页。有人可以指导我吗

1 个答案:

答案 0 :(得分:0)

希望它的工作

试试这个

mywebsite.com/index.php/user_get?id=1