构建REST APIs code Igniter

3
我正在尝试为我的网站开发REST APIs。我使用的是CodeIgniter的PHP框架。我按照此教程创建了restful apis。该教程基于这个代码库开发。
我将rest.php放置在应用程序/config文件夹中,并将REST_Controller.php放置在应用程序/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);
            }
        }
    }

I have a .htaccess file as below:

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

However when I send a GET Request to mywebsite.com/index.php/example/id/1 it redirects to the homepage. Could someone guide me


请尝试访问此网址 mywebsite.com/index.php/example/user/id/1 - umefarooq
@umefarooq,它不是那样工作的。我需要修改routes.php吗? - user1692342
我已经尝试了您的控制器,并使用CI 3的最新安装,没有遇到任何问题。我使用了以下URL:http://localhost/ci3/index.php/example/user/id/1。 - umefarooq
@umefarooq,按照您提到的在新安装上测试的方式进行测试时,它可以工作。但是在我的设置中,它不知道为什么无法工作:( - user1692342
@umefarooq 我有一个 .htaccess 文件,当 index.php 存在时会进行重定向 (RewriteRule ^(.*)$ index.php?/$1 [L])。我已经在我的机器上设置了一个虚拟主机。所以当我访问 dev.myweb.com/example 时,它会重定向到 dev.myweb.com。你知道为什么它无法访问我的控制器吗? - user1692342
我不确定你的库是如何工作的,但关于 .htaccess 部分,以下类型的方法可以使用(请原谅缺乏格式): RewriteRule ^partner/o/(.*)$ /path/ordering.php?recall=$1 [L] ... 在这种情况下,它将把 yoursite.com/partner/o/xxx 的 URL 转换为 yoursite.com/path/ordering.php?recall=xxx。脚本在变量 $_REQUEST['recall'] 中接收 "xxx"。你真的想要传递整个路径而不将其分配给一个变量吗? - amh15
1个回答

0
希望它能正常工作。
试一下这个。
mywebsite.com/index.php/user_get?id=1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接