定制 edulazaro/larasources 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

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 sources table (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 origin
  • save(): push current attributes to the origin and persist
  • saveToOrigin(): push without persisting locally
  • delete(): delete remote and clear cache
  • clear(): clear cached record only
  • origin(): get the resolved Origin instance
  • getRecord(): get the underlying SourceRecord (or null)
  • setVariant(string $variant): set the source's variant
  • setVariantArguments(array $args): pass runtime arguments

Origin

  • fetch(array $arguments): array
  • save(array $data): array
  • delete(): bool
  • regenerate(): array
  • getAlias(): string

Bundled abstract Origins

  • Origin: base class
  • RemoteOrigin: generic REST client base
  • AgentOrigin: for agent-style integrations
  • ScraperOrigin: for HTML scraping with getHtml() 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 我们能提供哪些服务?
定制开发 / 二次开发

基于 edulazaro/larasources 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 2
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 45
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-04-28