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

如何使用restful Web服务创建PHP Kohana应用程序?,php,rest,kohana,kohana-3,kohana-orm,Php,Rest,Kohana,Kohana 3,Kohana Orm,我对PHP和Kohana非常陌生。已经创建了一个示例/演示“hello World”PHP Kohana应用程序,该应用程序正在WAMP服务器中成功运行 我希望我的应用程序能够作为一个完整的服务器端组件工作 因为我在这个应用程序中只有服务器端逻辑,所以它应该使用ORM与我的MySQL数据库通信 我将有一个单独的客户端应用程序,它将有UI部分 因此,我希望我的PHP Kohana能够识别来自客户端的RestFul webservices调用,并相应地给出JSON响应 是否可以创建一个支持RestF

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

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

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

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

因此,我希望我的PHP Kohana能够识别来自客户端的RestFul webservices调用,并相应地给出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()方法中,可能是父控制器的before()方法中,以便它总是在从数据库获取数据之前运行

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

// Standard ajax response array.
$this->ajax_response = array(
    'success' => FALSE,
    'error' => NULL,
    'raw_data' => NULL,
    'generated' => ''
);
根据您的需要定制上述内容。您可能还希望在before()方法中使用此方法

现在,在动作方法中,从数据库获取数据并将其添加到数组中

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.';
    }
}
然后,您应该能够通过调用URL(如
http://www.website.com/controller/foobar/42

谜题的最后一部分实际上是返回这些数据,因为目前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);
    }
});
祝你好运,建立你的应用程序!我希望这至少能帮助你开始