Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Swap Laravel Package

florianv/swap

PHP 8.2+ currency exchange rate library with a single API over 30+ providers. Supports conversion, historical rates, PSR-16 caching, and provider fallback. Works with PSR-18 HTTP clients and PSR-17 factories for flexible integrations.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Laravel Compatibility: The package is designed for PHP 8.2+ and adheres to PSR standards (PSR-16 for caching, PSR-18/PSR-17 for HTTP). Laravel’s built-in HTTP client (symfony/http-client) and caching systems (e.g., Illuminate\Cache) are fully compatible, requiring minimal abstraction.
  • Domain Alignment: Swap is a specialized solution for currency conversion, aligning well with e-commerce, fintech, or multi-currency applications. It avoids reinventing wheel for generic HTTP requests.
  • Extensibility: Supports custom providers via Exchanger\Contract\ExchangeRateService, enabling integration with internal APIs or legacy systems.

Integration Feasibility

  • Low Friction: No Laravel-specific dependencies; integrates via Composer. The Builder pattern simplifies configuration (e.g., fallback chains).
  • Caching: Leverages PSR-16 (Symfony\Component\Cache\Adapter\AdapterInterface), which Laravel’s Cache facade can wrap seamlessly.
  • Error Handling: Built-in ChainException for provider fallbacks, which can be mapped to Laravel’s exception handling (e.g., render() in controllers).

Technical Risk

  • Provider Dependency: Commercial providers (e.g., fastforex) may introduce rate limits or cost over time. Public providers (e.g., ECB) are free but limited in scope.
  • Historical Data: Some providers lack historical rates; requires upfront validation for use cases needing time-series data.
  • Crypto Support: Limited to providers like coin_layer; may not meet all crypto-native applications’ needs.
  • Laravel-Specific Quirks: No native Laravel service provider or config publisher, requiring manual DI setup (e.g., binding Swap to the container).

Key Questions

  1. Use Case Scope:
    • Are you converting real-time rates (e.g., checkout) or historical rates (e.g., audits)?
    • Do you need crypto support, or is it fiat-only?
  2. Provider Strategy:
    • Will you use the free tier of fastforex or other commercial providers? What’s the cost/risk tolerance?
    • How will you handle provider failures (e.g., rate limits, outages) beyond the fallback chain?
  3. Caching Strategy:
    • Should rates be cached globally (e.g., Redis) or per-user (e.g., session-based)?
    • What’s the TTL for cached rates (e.g., 1 hour for volatile markets)?
  4. Observability:
    • How will you log/monitor provider performance (e.g., latency, errors)?
    • Do you need audit trails for rate sources (e.g., which provider returned a given rate)?
  5. Testing:
    • How will you mock providers in unit/integration tests (e.g., using Exchanger directly)?
    • Are there edge cases to test (e.g., unsupported currency pairs, malformed responses)?

Integration Approach

Stack Fit

  • PHP/Laravel: Native fit due to PSR compliance and Laravel’s alignment with Symfony components (e.g., HTTP client, caching).
  • Dependencies:
    • Required: florianv/swap, symfony/http-client, nyholm/psr7 (or alternatives like Guzzle).
    • Optional: moneyphp/money for advanced currency arithmetic (if using SwapExchange).
  • Alternatives:
    • Exchanger: Use if you need finer control over provider chains or HTTP logic.
    • Laravel Swap: If you prefer a pre-configured Laravel package (though this is a separate repo).

Migration Path

  1. Pilot Phase:
    • Start with a single provider (e.g., european_central_bank for free EUR-based rates).
    • Integrate into a non-critical feature (e.g., admin dashboard).
  2. Production Rollout:
    • Add commercial providers (e.g., fastforex) for broader coverage.
    • Implement fallback chains for redundancy.
  3. Optimization:
    • Configure caching (e.g., Redis with 5-minute TTL for volatile pairs).
    • Add logging for provider performance (e.g., Monolog channel).

Compatibility

  • Laravel Services:
    • Bind Swap to the container in AppServiceProvider:
      $this->app->singleton(Swap::class, function ($app) {
          return (new Builder())
              ->add('fastforex', ['api_key' => config('services.fastforex.key')])
              ->add('european_central_bank')
              ->useCache($app->make(\Illuminate\Contracts\Cache\Store::class))
              ->build();
      });
      
    • Inject Swap into controllers/services via constructor.
  • Configuration:
    • Store API keys in .env (e.g., FASTFOREX_API_KEY).
    • Use Laravel’s config/services.php for provider settings:
      'swap' => [
          'providers' => [
              'primary' => 'fastforex',
              'fallback' => ['european_central_bank', 'central_bank_of_republic_turkey'],
          ],
      ],
      

Sequencing

  1. Phase 1: Basic integration (1–2 providers, no caching).
  2. Phase 2: Add caching and fallback logic.
  3. Phase 3: Extend to historical rates or custom providers.
  4. Phase 4: Optimize for performance (e.g., bulk rate fetching, async updates).

Operational Impact

Maintenance

  • Provider Management:
    • Monitor API deprecations (e.g., if a provider changes its endpoint).
    • Rotate API keys if required by providers (e.g., fastforex free tier may have limits).
  • Caching:
    • Purge cache on rate updates (e.g., via Cache::forget() or scheduled jobs).
    • Handle cache stampedes for high-traffic applications (e.g., use probabilistic early expiration).
  • Dependencies:
    • Update florianv/swap and its dependencies (e.g., symfony/http-client) regularly.
    • Watch for breaking changes in PSR standards (e.g., PSR-18 HTTP client updates).

Support

  • Debugging:
    • Use ChainException to identify which provider failed in the chain.
    • Log provider responses for auditability (e.g., swap.provider.response channel).
  • User Communication:
    • Surface rate sources to users (e.g., "This rate is from fastFOREX").
    • Handle unsupported currencies gracefully (e.g., return a 400 error or fallback to a default rate).
  • Documentation:
    • Maintain an internal runbook for:
      • Provider-specific quirks (e.g., coin_layer requires crypto pairs to be lowercase).
      • Rate limit thresholds (e.g., fastforex free tier allows 1,000 requests/month).

Scaling

  • Performance:
    • Bulk Fetching: Use Swap::latest() for single pairs or implement batch requests for multiple pairs (e.g., via Exchanger).
    • Async Updates: For high-frequency applications, consider a background job to refresh rates (e.g., Laravel Queues + swap:refresh command).
  • Cost:
    • Commercial providers may incur usage-based fees (e.g., fastforex paid plans).
    • Optimize cache TTLs to balance freshness and cost (e.g., shorter TTLs for volatile pairs like USD/JPY).
  • Global Distribution:
    • If rates are used in multi-region apps, consider region-specific providers (e.g., central_bank_of_republic_turkey for TRY).

Failure Modes

Failure Scenario Impact Mitigation
Primary provider outage No rates available Fallback chain to secondary providers.
Rate limit exceeded 429 errors Implement exponential backoff or switch providers.
Unsupported currency pair InvalidArgumentException Return a default rate or notify the user.
Cache corruption Stale rates Use short TTLs or cache invalidation hooks.
Provider API changes Broken integrations Test against provider sandboxes; monitor changelogs.
High latency Poor UX (e.g., slow checkout) Cache aggressively; use async rate fetching.

Ramp-Up

  • Onboarding:
    • Developer Training:
      • Focus on the Builder pattern and provider configuration.
      • Demonstrate fallback chains and error handling.
    • Testing:
      • Provide mock providers for
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium