2016-07-29 29 views
2

我对PHP和Kohana非常新颖。已经创建了一个在WAMP服务器上成功运行的示例/演示“hello World”PHP Kohana应用程序。如何用平静的webservices创建一个PHP Kohana应用程序?

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

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

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

所以我想我的PHP-Kohana应该识别来自我的客户端的RestFul webservices调用,并相应地给出JSON响应。

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

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

是否有任何这样的示例代码演示?

回答

1

有没有具体的演示或示例代码,我知道的,所以希望这些提示将帮助您开始使用它...

这是可能的,而且比较容易,接受AJAX请求,并产生JSON对Kohana的回应。首先要注意的是,除非特别指出,Kohana的将总是尝试生成视图,首先会失败,因为一个JSON响应,以便第一件事:

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

你可能会想把它放在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.'; 
    } 
} 

然后,您应该能够通过调用一个网址,如http://www.website.com/controller/foobar/42

的最后一块拼图真的返回这个数据来请求这个数据,此刻的Kohana不会输出任何东西,因为我们已经告诉它不要。在你()方法之后,请执行下列操作:

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); 
    } 
}); 

好运与建立你的应用程序!我希望这有助于至少让你开始。

相关问题