如何在 Laravel 4 中组织不同版本的 REST API 控制器? [英] How to organize different versioned REST API controllers in Laravel 4?

查看:21
本文介绍了如何在 Laravel 4 中组织不同版本的 REST API 控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一种方法可以为带有路由的 REST API 创建版本化 URL,但是组织控制器和控制器文件的最佳方法是什么?我希望能够创建新版本的 API,并让旧版本至少运行一段时间.

I know there's a way to create versioned URLs for REST APIs with routes, but what's the best way to organize controllers and controller files? I want to be able to create new versions of APIs, and still keep the old ones running for at least some time.

推荐答案

我最终使用了 app/controllers 下的命名空间和目录:

I ended up using namespaces and directories under app/controllers:

/app
  /controllers
    /Api
      /v1
        /UserController.php
      /v2
        /UserController.php

在 UserController.php 文件中,我相应地设置了命名空间:

And in UserController.php files I set the namespace accordingly:

namespace Apiv1;

namespace Apiv2;

然后在我的路线中我做了这样的事情:

Then in my routes I did something like this:

Route::group(['prefix' => 'api/v1'], function () {
  Route::get('user',      'Apiv1UserController@index');
  Route::get('user/{id}', 'Apiv1UserController@show');
});

Route::group(['prefix' => 'api/v2'], function () {
  Route::get('user',      'Apiv2UserController@index');
  Route::get('user/{id}', 'Apiv2UserController@show');
});

我不肯定这是最好的解决方案.但是,它允许以不相互干扰的方式对控制器进行版本控制.如果需要,您可能可以对模型进行类似的验证.

I'm not positive this is the best solution. However, it has allowed versioning of the controllers in a way that they do not interfere with each other. You could probably do something verify similar with the models if needed.

这篇关于如何在 Laravel 4 中组织不同版本的 REST API 控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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