donglun4682
2018-03-23 11:30
浏览 67
已采纳

CodeIgniter 3 - 支持控制器中的API和Web请求?

I'm currently working with a CodeIgniter3 application, and have built the basis for a standard blog-like system.

The structure is standard CI - User requests a page, page loads controller method, controller method calls any relevant DB functions from its model, and then a view is loaded.

However, I'm looking to also make this view accessible via an API. So, instead of the $data array being filled with information to populate into HTML, I would instead pass it to a different view which would output a JSON result.

I imagine writing two different controllers would be a bad step to take - is there any routing I can do, or any standard practice to allow for the controllers to recognise an api endpoint has been hit (such as the directory 'api' being in the access path), and then load up a different view based on this?

图片转代码服务由CSDN问答提供 功能建议

我目前正在使用CodeIgniter3应用程序,并为类似博客的标准系统奠定了基础。 / p>

结构是标准CI - 用户请求页面,页面加载控制器方法,控制器方法从其模型调用任何相关的DB函数,然后加载视图。

但是,我还希望通过API访问此视图。 因此,不是将$ data数组填充到填充到HTML中的信息,而是将其传递给另一个输出JSON结果的视图。

我想要编写两个不同的控制器 这将是一个糟糕的步骤 - 是否有我可以做的任何路由,或任何标准的做法,以允许控制器识别api端点已被命中(例如目录'api'在访问路径中),然后 基于此加载不同的视图?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongying195959 2018-03-23 13:17
    已采纳

    For an API, I wouldn't use a view. Views are traditionally for HTML. I'd suggest instead of passing $data to a view, simply echo it out at the end of the controller like so.

    echo json_encode($data);
    

    I've created this wrapper to make extending how I return data flexible. Here's a basic example.

    function api_response($data = array()) {
        $data['error'] = false;
        function filter(&$value) {
            if (is_string($value)) {
                $value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
                $value = nl2br($value);
            }
        }
        array_walk_recursive($data, "filter");
        return json_encode($data);
    }
    

    And I use something like this for API errors

    function api_error_response($error_code, $error_message) {
        log_message('error', $error_code . ' - ' . $error_message);
        $data['error'] = true;
        $data['error_code'] = $error_code;
        $data['error_message'] = $error_message;
        return json_encode($data);
    }
    

    And then I call it like so at the end of a controller.

    echo api_response($data);
    

    Additionally, to be able to use the same controller methods for the API as you do for the web GUI, only duplicate the routes, and in the controller methods use something like this.

    // Return here for API
    if (strpos($_SERVER['REQUEST_URI'], '/api/') !== false) {
        // Unset any data you don't want through the API
        unset($data['user']);
        echo api_response($data);
        return false;
    }
    // Else, load views here
    
    点赞 打赏 评论

相关推荐 更多相似问题