消费我自己Laravel API [英] Consuming my own Laravel API

查看:281
本文介绍了消费我自己Laravel API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Laravel 4的应用程序,这将使通过一个JSON REST API和一个Web UI可我的数据集相同的CRUD操作。如此看来,以prevent打破了DRY原则,我的UI应该通过路由来自UI所有请求回API消耗我自己的API。我不能确定,虽然即将使这项工作的最佳方法。 presumably我有独立的用户界面和API控制器并以某种方式将请求路由通过。或者,我应该在不同的方法完全看?

I'm developing a Laravel 4 app that will make the same CRUD operations on my dataset 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?

感谢。

推荐答案

我实际上有同样的想法,修修补补,它是pretty整洁。随着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);

$回应现在将包含API返回的响应。通常,这将返回一个JSON EN codeD字符串,它是伟大的客户,但不是伟大的内部API请求。你必须在这里延长了一些东西,但基本思路是通过回为内部调用返回实际的对象,而外部请求返回格式化的JSON响应。您可以使用的东西像 $响应 - 方式> 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.

你应该看看这样做是构建一些内部调度,允许你调度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天全站免登陆