消费自己的Laravel API时如何遵循不重复原理? [英] How Follow the Don't Repeat Yourself Principle When Consuming My Own Laravel API?

查看:42
本文介绍了消费自己的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版本,然后选择最佳的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天全站免登陆