简体   繁体   English

cakePHP中的RESTful Web服务

[英]RESTful web service in cakePHP

I followed the tutorial on this website which explains how to setup REST with cakePHP, but after I did all this, when I call my controller in the browser (for example I have a PostsController which has the default CRUD actions), I still get html as my response (not xml). 我遵循了该网站上的教程, 教程解释了如何使用cakePHP设置REST,但是在完成所有这些之后,当我在浏览器中调用控制器时(例如,我有一个具有默认CRUD操作的PostsController),我仍然得到了html作为我的回应(不是xml)。 It seems like the view file that's being called is the one in app/views/posts/index.ctp instead of the one I placed in app/views/posts/xml/index.ctp . 似乎正在调用的视图文件是app/views/posts/index.ctp中的一个,而不是我放在app/views/posts/xml/index.ctp

Can anybody tell me what else I am missing here please? 有人可以告诉我在这里我还想念什么吗?

Thank you 谢谢

What version of cakePHP are you using? 您正在使用哪个版本的cakePHP? If you are using versions 2.x, the solution is very simple. 如果您使用的是2.x版本,则解决方案非常简单。

  1. Make sure you include this line in your controller 确保在控制器中包含此行

     public $components = array('RequestHandler'); 
  2. Go into your app/Config/routes.php and add the following lines BEFORE the line with require CAKE . 'Config' . DS . 'routes.php'; 进入您的app / Config / routes.php并在require CAKE . 'Config' . DS . 'routes.php';行之前添加以下行require CAKE . 'Config' . DS . 'routes.php'; require CAKE . 'Config' . DS . 'routes.php'; :

     Router::mapResources('examples'); Router::parseExtensions('xml'); 

    Where examples is essentially just the name of your view. 示例实际上只是您的视图名称。

  3. Be sure to enter the your url with the xml extension. 确保输入带有xml扩展名的URL。

     url/controller.xml 

This should do the trick. 这应该可以解决问题。 Including the RequestHandler component, when "used in conjunction with Router::parseExtensions() RequestHandler, will automatically switch the layout and view files to those that match the requested type" 包括RequestHandler组件,当“与Router :: parseExtensions()RequestHandler结合使用时,将自动将布局和视图文件切换为与所请求类型匹配的文件”

Did you create an xml layout? 您是否创建了xml布局? You might need to just create a blank layout and in the view set the layout to the xml layout. 您可能只需要创建一个空白布局,然后在视图中将该布局设置为xml布局即可。

Try putting something like this in your controller function (or even better in the beforeFiler): 尝试在控制器函数中放这样的东西(或者在beforeFiler中更好):

if(@($this->request->isXML() || $this->request->params['ext'] == 'xml')) {
    $this->RequestHandler->respondAs('xml');
}

Also make sure in Config/routes.php is 还要确保在Config / routes.php中

Router::parseExtensions('xml');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM