如何使用restful Web服务创建PHP Kohana应用程序


How can I create a PHP Kohana application with restful webservices?

我对PHP和Kohana非常陌生。已经创建了一个示例/演示"helloWorld"PHP Kohana应用程序,该应用程序正在WAMP服务器上成功运行。

我希望我的应用程序作为一个完整的服务器端组件来工作。

由于我在这个应用程序中只有服务器端逻辑,所以它应该使用ORM与我的MySQL数据库通信。

我将有一个单独的客户端应用程序,它将有UI部分。

因此,我希望我的PHP Kohana能够识别来自客户端的RestFul Web服务调用,并相应地给出JSON响应。

是否可以创建一个支持RestFul Web服务的Kohana应用程序?

如果是,请给我一个在Kohana应用程序中创建Web服务的指导。

有这样的演示示例代码吗?

我还不知道具体的演示或示例代码,所以希望这些技巧能帮助你开始使用它…

使用Kohana接受AJAX请求并生成JSON响应是可能的,而且相对容易。首先要注意的是,除非另有说明,否则Kohana将始终尝试生成视图,而这将作为JSON响应失败,因此首先要注意:

if ($this->request->is_ajax()) {
    // Disable any rendering of the template so it just returns json.
    $this->auto_render = FALSE;
}

您可能希望将其放在before()方法中,可能是父控制器的方法,这样它总是在您从DB获取数据之前运行。

我个人倾向于设置一个标准的AJAX响应数组,这样数据总是以相对标准的格式返回。示例:

// Standard ajax response array.
$this->ajax_response = array(
    'success' => FALSE,
    'error' => NULL,
    'raw_data' => NULL,
    'generated' => ''
);

自定义以上内容以匹配您所需的用法。您可能还希望在before()方法中使用此方法。

现在,在您的操作方法中,从DB中获取数据并将其添加到数组中。

public function action_foobar() {
    // Get the primary key ID from the URL.
    $var1 = $this->request->param('var1');
    $data = ORM::factory('Model', $var1);
    if ($data->loaded()) {
        $this->ajax_response['success'] = TRUE;
        $this->ajax_response['raw_data'] = $data;
    } else {
        $this->ajax_response['error'] = 'Data could not be found.';
    }
}

然后,您应该能够通过调用诸如http://www.website.com/controller/foobar/42 之类的URL来请求这些数据

最后一块拼图实际上是返回这些数据,因为目前Kohana不会输出任何东西,因为我们已经告诉它不要输出。在after()方法中,执行以下操作:

if ($this->request->is_ajax()) {
    $this->request->headers('Content-Type', 'application/json');
    $this->response->body(json_encode($this->ajax_response));
}

然后,您可以在客户端应用程序的jQuery中自由地解释该响应:

$.ajax({
    type: "POST",
    url: "http://www.website.com/controller/foobar/" + foobarId,
    dataType: 'json',
    success: function (data) {
        if (!data.success) {
            alert(data.error);
        } else {
            // Handle the returned data.
        }
    },
    error: function (xhr, status, errorThrown) {
        // Something went very wrong (response failed completely).
        alert(errorThrown);
    }
});

祝你构建应用程序好运!我希望这至少能帮助你开始。