edulazaro/larasources
Composer 安装命令:
composer require edulazaro/larasources
包简介
Integrate external data sources into Laravel models with caching, retry and rate-limiting. Sources are model-like classes; Origins are pluggable API clients.
README 文档
README
A Laravel package for integrating external data sources into your models with caching, retry, and rate-limiting built in. Work with external APIs using model-like abstractions, without forcing those APIs to live in your own database tables.
Why
Larasources lets your Eloquent models pull and push data from external services through a typed, declarative Source API. Each source declares its fillable fields, casts, mappings, and origin (the API client). Your domain model stays clean, the integration layer stays separated, and the cached external state lives in a single dedicated table.
Features
- Model-like Sources: define external resources as classes with
fillable,casts, accessors, and arguments - Origins: pluggable API clients (
fetch,save,delete) decoupled from the data shape - Built-in caching through the
sourcestable (SourceRecord) - Variants and arguments to handle multiple operations or per-call parameters
- Retry and rate-limiting declared in config, applied automatically
- Mockable for tests via
mockSource()
Requirements
- PHP
>=8.4(any future version included) - Laravel
>=9.0(any future version included)
Installation
composer require edulazaro/larasources
Publish the configuration and migrations:
php artisan vendor:publish --provider="EduLazaro\Larasources\LarasourcesServiceProvider"
php artisan migrate
Configuration
Origin-specific credentials live in config/larasources.php under origins, keyed by your origin's alias:
'origins' => [ 'my_provider' => [ 'api_key' => env('MY_PROVIDER_API_KEY'), 'sandbox' => env('MY_PROVIDER_SANDBOX', false), ], ],
Then in .env:
MY_PROVIDER_API_KEY=your_api_key MY_PROVIDER_SANDBOX=true
Usage
1. Add the HasSources trait to your model
use Illuminate\Database\Eloquent\Model; use EduLazaro\Larasources\Concerns\HasSources; use App\Sources\WeatherSource; class City extends Model { use HasSources; protected array $sources = [ 'weather' => WeatherSource::class, ]; }
2. Read and write through the source
$city = City::find(1); // Access external data (autoloaded from cache or fetched on miss) $weather = $city->source('weather'); echo $weather->temperature; echo $weather->humidity; // Push data to the external API and persist locally $city->source('weather')->save(); // Force refresh from the API (bypasses cache) $fresh = $city->source('weather')->fetch(); // Delete remote and clear cache $city->source('weather')->delete();
3. Define a Source
namespace App\Sources; use EduLazaro\Larasources\Source; use EduLazaro\Larasources\Attributes\UsesOrigin; use App\Origins\MyProviderOrigin; #[UsesOrigin(MyProviderOrigin::class)] class WeatherSource extends Source { protected $fillable = [ 'temperature', 'humidity', 'description', ]; protected $casts = [ 'temperature' => 'float', 'humidity' => 'integer', ]; protected function arguments(): array { return [ 'city_id' => 'external_id', // maps to $city->external_id ]; } public function getFeelsLikeAttribute(): float { return $this->temperature - ($this->humidity / 10); } }
4. Define an Origin (the API client)
namespace App\Origins; use EduLazaro\Larasources\Origins\Origin; use Illuminate\Support\Facades\Http; class MyProviderOrigin extends Origin { public static function getAlias(): string { return 'my_provider'; } public function fetch(array $arguments = []): array { $response = Http::withToken($this->getConfig('api_key')) ->get('https://api.example.com/weather/' . $arguments['city_id']); return $response->json(); } public function save(array $data): array { $response = Http::withToken($this->getConfig('api_key')) ->post('https://api.example.com/weather', $data); return $response->json(); } public function delete(): bool { return true; } }
5. Variants and arguments
Use variants to handle multiple modes per source (for example, sale vs rent for a property listing, or current vs forecast for weather):
$city->source('weather')->setVariant('forecast')->fetch(); // Pass runtime arguments $city->source('weather', ['city_id' => 'custom_id'])->fetch();
Caching
Sources are cached automatically in the sources table (the SourceRecord model). Each record is keyed by (sourceable, name, variant).
// Has it ever been fetched/saved? if ($source->getRecord()) { // Data is cached locally } // Clear the cache for this source $source->clear();
Error handling
use EduLazaro\Larasources\Exceptions\OriginException; try { $weather = $city->source('weather')->fetch(); } catch (OriginException $e) { Log::error('Provider error: ' . $e->getMessage()); }
Testing
Mock a source so it returns a fixed instance instead of hitting the origin:
$mock = new WeatherSource(['temperature' => 22.5, 'humidity' => 60]); $city->mockSource(WeatherSource::class, $mock); $weather = $city->source('weather'); // $weather is the mocked instance
API reference
Source
fetch(): pull fresh data from the originsave(): push current attributes to the origin and persistsaveToOrigin(): push without persisting locallydelete(): delete remote and clear cacheclear(): clear cached record onlyorigin(): get the resolved Origin instancegetRecord(): get the underlyingSourceRecord(ornull)setVariant(string $variant): set the source's variantsetVariantArguments(array $args): pass runtime arguments
Origin
fetch(array $arguments): arraysave(array $data): arraydelete(): boolregenerate(): arraygetAlias(): string
Bundled abstract Origins
Origin: base classRemoteOrigin: generic REST client baseAgentOrigin: for agent-style integrationsScraperOrigin: for HTML scraping withgetHtml()helper
Credits
Developed by Edu Lázaro.
License
MIT
edulazaro/larasources 适用场景与选型建议
edulazaro/larasources 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 04 月 28 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「caching」 「laravel」 「integration」 「eloquent」 「rate-limiting」 「external-api」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 edulazaro/larasources 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 edulazaro/larasources 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 edulazaro/larasources 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Query caching for Laravel 5
LinkedIn API PHP SDK with OAuth 2.0 & CSRF support. Can be used for social sign in or sharing on LinkedIn. Examples. Documentation.
LinkedIn API PHP SDK with OAuth 2.0 & CSRF support. Can be used for social sign in or sharing on LinkedIn. Examples. Documentation.
Simple PHP caching system that uses a tmp folder in a Linux environment.
Provides support for PSR-6 compatible cache for Yii1 application
Laravel integration for blade-to-react
统计信息
- 总下载量: 2
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 45
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-04-28