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?

推荐答案

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()这样的东西来做这类事情.

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

这个 idea 本身是可靠的.但规划API是一项艰巨的工作.我建议你写一个很好的列表,列出所有预期的端点,起草几个API版本,然后 Select 最好的一个.

Laravel相关问答推荐

密码确认在Livewire中不匹配

运行NPM Prod时出现VUE问题

如何在 Laravel 中使用 return 停止 Trait php 的执行

如何使用 laravel 更新单个值

Laravel 模型事件:delete() 不会从存储中删除文件

Laravel 5.3:语法错误或访问冲突:1463 HAVING 子句中使用了非分组字段距离

语法错误或访问冲突:1115 未知字符集:utf8mb4

Laravel 将 JSON 转换为数组?

有条件的Eager加载

使用模型工厂、一对一和一对多关系定义 Laravel 外键,而不创建不必要的模型

在 Laravel 中生成随机数

如何更改默认 Laravel Auth 登录视图

在 Laravel 中,如何获取 *only* POST 参数?

如何运行artisan命令计划:在托管服务器上运行? (Laravel )

Laravel - 语法错误,文件意外结束

Laravel - 动态创建表(无需迁移)

如何在 Laravel 5 中的每个相关输入字段旁边显示验证错误?

Laravel 集合计数结果

如何在 Laravel 5.3 中获取当前的语言环境

在 Laravel 中翻译特定语言