robertogallea / eloquent-api
基于 Rest API 的 Eloquent 模型
Requires
- php: ^7.3|^7.4|^8
- ext-json: *
- calebporzio/sushi: ^2.0
- guzzlehttp/guzzle: ^6.5|^7
Requires (Dev)
- mockery/mockery: ^1.1
- orchestra/testbench: ~5|~6|~7
- phpunit/phpunit: ~8.5
- sempro/phpunit-pretty-print: ^1.0
This package is auto-updated.
Last update: 2024-09-16 12:35:45 UTC
README
一个允许你在 JSON Web API 之上放置 Eloquent 的包。
此包提供了一个位于 JSON Web API 端点之上的 Eloquent 模型。
当你使用此包时,模型的初始调用将对 HTTP 端点发出一个或多个请求,读取数据并将其转换为行数组。每行存储为基于文件的 sqlite 数据库中的表中的记录。后续对模型的调用将使用该 sqlite 数据库,因此底层数据的变化不会反映在数据库中。然而,有两种方式可以使 sqlite 缓存失效并重新创建它
-
你可以在模型上调用
invalidateCache()
方法,例如YourApiModel::first()->invalidateCache()
-
通过向此包提供的路由发送请求,删除 sqlite 数据库,强制下次使用模型时重新加载。
安装
composer require robertogallea/eloquent-api
使用方法
考虑以下 JSON 响应,由端点 https://ghibliapi.herokuapp.com/films
提供
[ { "id": "2baf70d1-42bb-4437-b551-e5fed5a87abe", "title": "Castle in the Sky", "description": "The orphan Sheeta inherited a mysterious crystal that links her to the mythical sky-kingdom of Laputa. With the help of resourceful Pazu and a rollicking band of sky pirates, she makes her way to the ruins of the once-great civilization. Sheeta and Pazu must outwit the evil Muska, who plans to use Laputa's science to make himself ruler of the world.", "director": "Hayao Miyazaki", "producer": "Isao Takahata", "release_date": "1986", "rt_score": "95", "people": [ "https://ghibliapi.herokuapp.com/people/" ], "species": [ "https://ghibliapi.herokuapp.com/species/af3910a6-429f-4c74-9ad5-dfe1c4aa04f2" ], "locations": [ "https://ghibliapi.herokuapp.com/locations/" ], "vehicles": [ "https://ghibliapi.herokuapp.com/vehicles/" ], "url": "https://ghibliapi.herokuapp.com/films/2baf70d1-42bb-4437-b551-e5fed5a87abe" }, { "...": "..." } ]
我们想在它上面放置一个 Eloquent 模型。
php artisan make:api-model
步骤 1 - 输入你想要创建模型文件的目录的完整路径(默认为 app_path()
)
步骤 2 - 输入你想要使用的模型类名称
步骤 3 - 粘贴你的资源端点
步骤 4 - 如果你的数据包含在特定的字段中,请输入其名称
步骤 5 - 如果你的资源是分页的,请输入包含下一页 URL 的 JSON 字段
步骤 6 - 确认路径和完整类名是否正确
生成的模型类
use robertogallea\EloquentApi\ApiModel; class YourApiModel extends ApiModel { protected $endpoint = 'https://ghibliapi.herokuapp.com/films'; // The endpoint protected $nextPageField = null; protected $dataField = null; }
处理包装资源
如果你的资源数据被包装在特定的 JSON 键中,你需要通过设置模型属性 $dataField
来告诉模型该键是什么。例如
protected $dataField = 'data';
处理分页数据
如果你的端点提供分页数据,此包支持多页抓取。在这种情况下,你只需要将 $nextPageField
属性设置为包含包含下一页链接的 JSON 字段名称的字符串,例如
protected $nextPageField = 'next_page_url';
此模型可以执行基本的 Eloquent 模型功能,因为它实际上是一个 Eloquent 模型。尽管它目前仅限于读取/列表方法。更新和插入目前不起作用。
问题、问题和拉取请求
你可以在 问题部分 报告问题并提出问题。请以 ISSUE: 开始你的问题,以 QUESTION 开始你的问题
如果你有问题,请首先查看已关闭的问题。随着时间的推移,我已经能够回答很多问题。
要提交拉取请求,请先叉 fork 此存储库,创建一个新的分支,并将你的新/更新代码提交到其中。然后从你的新分支打开拉取请求。有关更多信息,请参阅 此指南。