在使用我自己的 Laravel API 时如何遵循不要重复自己的原则? [英] How Follow the Don't Repeat Yourself Principle When Consuming My Own Laravel API?

查看:34
本文介绍了在使用我自己的 Laravel API 时如何遵循不要重复自己的原则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Laravel 4 应用程序,它将通过 JSON REST API 和 Web UI 对我的数据集进行相同的 CRUD 操作.似乎是为了防止打破 DRY 原则,即我的 UI 应该通过将所有请求从 UI 路由回 API 来使用我自己的 API.我不确定使这项工作的最佳方法.大概我会有单独的 UI 和 API 控制器,并以某种方式路由请求.还是我应该完全考虑不同的方法?

I'm developing a Laravel 4 app that will make the same CRUD operations on my data set available through a JSON REST API and a Web UI. It seems that to prevent breaking the DRY principle that my UI should consume my own API by routing all requests from the UI back to the API. I'm unsure though about the best approach to making this work. Presumably I would have separate UI and API controllers and somehow route the requests through. Or should I be looking at a different approach altogether?

推荐答案

我实际上也在修改相同的想法,而且它非常简洁.使用 Laravel,您确实可以发出内部请求(有些人可能将其称为 HMVC,但我不会).以下是内部请求的基础知识.

I'm actually tinkering with the same idea and it's pretty neat. With Laravel you do have the ability to make internal requests (some might refer to this as HMVC, but I won't). Here's the basics of an internal request.

$request = Request::create('/api/users/1', 'GET');

$response = Route::dispatch($request);

$response 现在将包含 API 的返回响应.通常,这将返回一个 JSON 编码的字符串,这对客户端来说很好,但对内部 API 请求来说不是很好.你必须在这里扩展一些东西,但基本上这个想法是为内部调用返回实际对象,对于外部请求返回格式化的 JSON 响应.您可以在此处使用 $response->getOriginalContent() 之类的东西.

$response will now contain the returned response of the API. Typically this will be returned a JSON encoded string which is great for clients, but not that great for an internal API request. You'll have to extend a few things here but basically the idea is to return the actual object back through for the internal call, and for external requests return the formatted JSON response. You can make use of things like $response->getOriginalContent() here for this kind of thing.

您应该考虑构建某种内部Dispatcher,它允许您调度 API 请求并返回原始对象.调度员还应该处理格式错误的请求或错误的响应并抛出异常以进行匹配.

What you should look at doing is constructing some sort of internal Dispatcher that allows you to dispatch API requests and return the original object. The dispatcher should also handle malformed requests or bad responses and throw exceptions to match.

这个想法本身是可靠的.但是规划 API 是一项艰巨的工作.我建议您编写一份包含所有预期端点的清单并起草几个 API 版本,然后选择最好的一个.

The idea itself is solid. But planning an API is hard work. I'd recommend you write up a good list of all your expected endpoints and draft a couple of API versions then select the best one.

这篇关于在使用我自己的 Laravel API 时如何遵循不要重复自己的原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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