iafilin/eloquenthttpadapter
Composer 安装命令:
composer require iafilin/eloquenthttpadapter
包简介
EloquentHttpAdapter is a Laravel package that allows you to work with RESTful API data using an Eloquent-like syntax with HttpModel abstract class, interfaces, and custom exceptions.
关键字:
README 文档
README
EloquentHttpAdapter
EloquentHttpAdapter is a Laravel package that provides an alternative to calebporzio/sushi. It allows you to work with RESTful API data using an Eloquent-like syntax.
This package was originally developed to integrate Filament with APIs, making it a convenient tool for admin panels. However, thanks to its flexibility, it can also be used for any task requiring API integration with an Eloquent-like interface.
Installation
Install the package via Composer:
composer require iafilin/eloquenthttpadapter
Usage
Setting Up a Model
To enable API integration, use the InteractsWithHttp trait and define a custom httpClient method to configure the HTTP client:
namespace App\Models; use Iafilin\EloquentHttpAdapter\InteractsWithHttp; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Client\PendingRequest; class Purchase extends Model { use InteractsWithHttp; /** * Configure the HTTP client with the API endpoint. */ private static function httpClient(): PendingRequest { return \Http::baseUrl('/api/admin/purchases'); } }
Registering a Fetch Parameters Resolver
You can define the logic for building HTTP query parameters using the registerFetchParamsResolver method. This allows dynamic configuration of pagination, filtering, and sorting parameters.
Additionally, within the resolver, you have access to the getQuery() object, which lets you retrieve Eloquent wheres conditions and use them to generate HTTP parameters.
Example setup:
class Purchase extends Model { use InteractsWithHttp; protected static function boot() { parent::boot(); static::registerFetchParamsResolver(function ($page, $perPage) { $params = [ 'page' => $page, 'per_page' => $perPage), ]; // Parse `wheres` from the query object foreach ($this->getQuery()->wheres as $where) { $params["filter[{$where['column']}"] = $where['value']; } return $params; }); } }
API Requirements
To ensure compatibility with the package, your API should follow these conventions:
-
Standard REST endpoints:
POST /api/resource— Create records.GET /api/resource— Fetch records (paginated or full list).GET /api/resource/{id}— Fetch a single record.PUT /api/resource/{id}— Update a record.DELETE /api/resource/{id}— Delete a record.
-
Response Structure:
- Lists: Should include
data,total,per_page, andcurrent_page. - Single Record: Should return attributes directly without nesting.
- Lists: Should include
Example paginated response:
{
"data": [
{ "id": 1, "name": "Item 1" },
{ "id": 2, "name": "Item 2" }
],
"total": 50,
"per_page": 10,
"current_page": 1
}
-
Pagination:
- Support for
pageandper_pagequery parameters.
- Support for
-
Filters and Sorting:
- Filters:
filter[column]=value. - Sorting:
sort=columnfor ascending andsort=-columnfor descending.
- Filters:
CRUD Operations
Once your model is set up, you can use standard Eloquent methods to interact with your API:
Create a Record
$purchase = Purchase::create(['name' => 'New Item']);
Read Records
$purchases = Purchase::all(); // Fetch all records $purchases = Purchase::paginate(10); // Paginate results
Update a Record
$purchase = Purchase::find(1); $purchase->update(['name' => 'Updated Name']);
Delete a Record
$purchase = Purchase::find(1); $purchase->delete();
Customizing HTTP Requests
You can fully customize HTTP request behavior by overriding the httpClient method in your model. For example, adding headers or specific configurations:
private static function httpClient(): PendingRequest { return \Http::baseUrl('/api/admin/purchases') ->withHeaders(['Authorization' => 'Bearer token']); }
If you have any questions or suggestions, feel free to open an issue or contribute! 💡
Customizing API Fetch Parameters with registerFetchParamsResolver
The registerFetchParamsResolver method allows you to customize the HTTP query parameters sent to your API for fetching data. It provides a powerful way to dynamically build parameters like pagination, filters, and sorting based on the current Eloquent query or incoming user requests.
With access to the Eloquent query object ($this->getQuery()), you can parse wheres, orders, and other query conditions, transforming them into HTTP parameters compatible with your API.
Key Benefits:
- Dynamic configuration: Automatically adapt HTTP query parameters to match user input or specific query requirements.
- Seamless integration: Utilize existing Eloquent query methods while maintaining API compatibility.
- Support for complex queries: Build filters, pagination, and sorting logic based on both application and API needs.
Example Usage:
class Purchase extends Model { use InteractsWithHttp; protected static function boot() { parent::boot(); static::registerFetchParamsResolver(function () { $params = [ 'page' => request()->query('page', 1), 'per_page' => request()->query('per_page', 10), ]; // Parse where conditions from the query object foreach ($this->getQuery()->wheres as $where) { $params["filter[{$where['column']}"]"] = $where['value']; } return $params; }); } }
This makes it easy to dynamically adapt HTTP query parameters based on user input or predefined conditions in your Laravel application.
Error Handling
The package automatically logs errors during API interactions and returns null in case of failure. This ensures graceful handling of API downtime or errors without throwing exceptions.
License
This package is open-source and licensed under the MIT license.
iafilin/eloquenthttpadapter 适用场景与选型建议
iafilin/eloquenthttpadapter 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 287 次下载、GitHub Stars 达 8, 最近一次更新时间为 2024 年 11 月 14 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「http」 「rest」 「exceptions」 「api」 「adapter」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 iafilin/eloquenthttpadapter 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 iafilin/eloquenthttpadapter 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 iafilin/eloquenthttpadapter 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
php7ify is a project that brings new php7 classes and exceptions to php 5.x.
repository php library
The CodenamePHP Platform core that contains basic interfaces, exceptions etc..
A simple package to better handle Exceptions.
A PSR-7 compatible library for making CRUD API endpoints
Api bundle
统计信息
- 总下载量: 287
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 8
- 点击次数: 16
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-11-14