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

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?

  • 写回答

1条回答 默认 最新

  • dongying195959 2018-03-23 05: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
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 在更新角色衣服索引后,Sprite 并未正确显示更新的效果该如何去解决orz(标签-c#)
  • ¥15 VAE代码如何画混淆矩阵
  • ¥15 求遗传算法GAMS代码
  • ¥15 雄安新区高光谱数据集的下载网址打不开
  • ¥66 android运行时native和graphics内存详细信息获取
  • ¥100 求一个c#通过CH341读取数据的Demo,能够读取指定地址值的功能
  • ¥15 rk3566 Android11 USB摄像头 微信
  • ¥15 torch框架下的强化学习DQN训练奖励值浮动过低,希望指导如何调整
  • ¥35 西门子博图v16安装密钥提示CryptAcquireContext MS_DEF_PROV Error of containger opening
  • ¥15 mes系统扫码追溯功能
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部