Laravel 4 RESTful Api with content negotiation

≡放荡痞女 提交于 2019-12-23 04:59:10

问题


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.

My API router is:

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

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?


回答1:


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.

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).

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

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.

Hope that helps.



来源:https://stackoverflow.com/questions/18196184/laravel-4-restful-api-with-content-negotiation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!