CakePHP的REST API删除.format的必要性 [英] Cakephp REST API remove the necessity of .format
问题描述
我的工作创造一个REST API,将只能获得并返回JSON数据。
I am working on creating a REST api that will only get and return JSON data.
我在下面的蛋糕指南和我的默认路由是这样的:
I'm following the cake guide and my default routes are like this:
GET /recipes.format
GET /recipes/123.format
POST /recipes.format
PUT /recipes/123.format
DELETE /recipes/123.format
POST /recipes/123.format
不过,我真的不喜欢使用.format(在我的情况以.json),因为我将永远只能接受JSON的必要性。
However, I really dislike the necessity of using the ".format" (".json" in my case) since I will only ever be accepting json.
我觉得必须有一个方法来消除这种必要性。我可以使用的.htaccess重写URL,但我觉得必须有一个办法在一个地方设置蛋糕/ config文件来做到这一点。
I feel like there has to be a way to remove this necessity. I could use .htaccess to rewrite URLS, but I feel like there must be a way to do this in a cake setting / config file somewhere.
总之,我希望安倍 GET /食谱
键,把它的输出同样的事情 GET /recipes.json
会。
In short, I want to be abe to GET /recipes
and have it output the same thing as GET /recipes.json
would.
谢谢!
推荐答案
我假设你正在使用<$c$c>RequestHandler$c$c>组件。再一个办法是很难code在控制器的扩展 beforeFilter()
回调:
I assume you are using the RequestHandler
component. One way would then be to hardcode the extension in your controllers beforeFilter()
callback:
public function beforeFilter()
{
parent::beforeFilter();
$this->RequestHandler->ext = 'json';
}
这样,它总是使用JSON查看和合适的响应头,即使扩展解析已启用,非以.json扩展在URL中提供。
That way it would always use the JSON View and appropriate response headers, even if extension parsing is enabled and a non-.json extension was supplied in the URL.
另一种选择是使用<一href=\"http://book.cakephp.org/2.0/en/core-libraries/components/request-handling.html#RequestHandlerComponent%3a%3arenderAs\"><$c$c>RequestHandlerComponent::renderAs()$c$c>在各个控制器动作:
Another option would be to use RequestHandlerComponent::renderAs()
in your individual controller actions:
public function index()
{
$this->RequestHandler->renderAs($this, 'json');
...
}
这将有同样的效果,但你需要做的这一切行动的,所以万一控制器仅目的是为了处理REST请求,你可能会更好过覆盖扩展。
That would have the same effect, but you would need to do this in all of your actions, so in case the controllers solely purpose is to handle REST requests, you are probably better off overriding the extension.
这篇关于CakePHP的REST API删除.format的必要性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!