问题描述
我正在开发一个 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 时如何遵循不要重复自己的原则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!