Laravel 4的RESTful API和内容协商 [英] Laravel 4 RESTful Api with content negotiation

查看:212
本文介绍了Laravel 4的RESTful API和内容协商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在laravel一个RESTful API的工作,我想在我的项目中使用内容协商,但我不知道如何来实现这一目标。
我有我的控制器通过API版本separted,我想API版本之间的区别和使用正确的controllerdepending上的版本。

I'm working in a RESTFul API with laravel, and I want to use content negotiation in my project, but I don't know how to accomplish that. I have my controllers separted by api version, and I want to distinguish between api versions and use the correct controllerdepending on the version.

我的API路由器是:

Route::group(array('prefix' => 'api'), function() {
    Route::resource('users', 'API\V1\UsersController');
});

我应该创建一个过滤器api.type在我的路线组使用或者我应该做的,在航线组clousure或者,每个控制器?

Should I create a api.type filter to use in my route group or Should I do that in the route group clousure or maybe, in each controller?

推荐答案

不要害怕你的应用程序逻辑拓展到库类。你不必适合Laravel的特定文件夹结构内的一切。

Don't be afraid to branch out your application logic into library classes. You don't have to fit everything inside of Laravel's given folder structure.

事实上,加入在自己的命名空间的类组可以有一个很大的好处。你可以看到在这里创建自己的应用程序库。

In fact, adding in your own namespaced group of classes can have a big benefit. You can see some setup on creating your own application library here.

一旦你的设置,你可以创建一个类,其责任是决定什么内容类型返回。这可能是基于一个接受标题,URL参数或任何你定义(这是给你的API创建者)。

Once you have that set up, you can create a class whose responsibility is to decide what content type to return. This might be based on an Accept header, URL parameter or whatever you define (That's up to you, the API creator).

也许这班将采取 接受 头和它规范化为类似JSON,XML和HTML。

Perhaps this class will take the Accept header and normalize it to something like "json", "xml" and "html".

Request类有<一个href=\"https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/Request.php#L1300\"相对=nofollow>一些 的方法来帮助你,如果你通过接受头做到这一点。

The Request class has some methods to help you if you do it via the Accept header.

所以,在伪code (语法错误跟随!),你的控制器可能做这样的事情:

So, in pseudo code (syntax errors to follow!), your controller might do something like this:

/* GET /api/users */
public function index()
{
    // Might return "json" or "xml" or "html"
    $contentType = \My\ContentType\Class->getContentType();

    $users = User::all();

    // Not shown here is logic to set `content-type` header in the returned response (json vs xml vs html)
    // Perhaps a method to go into your implementation of \My\ContentType\Class
    return View::make('users.'.$contentType)->with(array( 'users' => $users ));


}

这只是你可能会做什么的想法。关键的一点是让自己,你可以把业务逻辑转换,让你开始与如何完成增加业务逻辑为您的应用想法图书馆工作。

That's just an idea of what you might do. The key point is to get yourself working in a library that you can put business logic into to get you started with an idea of how to accomplish adding in business logic for your application.

希望有所帮助。

这篇关于Laravel 4的RESTful API和内容协商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆