带有内容协商的 Laravel 4 RESTful Api [英] Laravel 4 RESTful Api with content negotiation

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

问题描述

我正在使用 laravel 使用 RESTFul API,我想在我的项目中使用内容协商,但我不知道如何实现.我的控制器按 api 版本分开,我想区分 api 版本并根据版本使用正确的控制器.

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 路由器是:

My API router is:

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.

设置好后,您可以创建一个类,该类的职责是决定要返回的内容类型.这可能基于 Accept 标头、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 类有一些 方法来帮助你如果您通过 Accept 标头执行此操作.

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

因此,在伪代码(要遵循语法错误!)中,您的控制器可能会执行以下操作:

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天全站免登陆