CodeIgniter3 - supporting both API & Web requests in Controllers?

坚强是说给别人听的谎言 提交于 2019-12-06 08:40:13

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!