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

Reference Currency Laravel Package

baks-dev/reference-currency

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require baks-dev/reference-currency
    

    Ensure your composer.json specifies PHP 8.4+ and Laravel 10+ (or equivalent framework).

  2. Publish Config (if needed)

    php artisan vendor:publish --provider="BaksDev\ReferenceCurrency\CurrencyServiceProvider" --tag="config"
    

    Check config/currency.php for default settings (e.g., API endpoints, caching).

  3. First Use Case Fetch the latest exchange rates for a currency (e.g., USD to RUB):

    use BaksDev\ReferenceCurrency\Facades\Currency;
    
    $rates = Currency::getRates('USD', ['RUB', 'EUR']);
    // Returns: ['RUB' => 90.5, 'EUR' => 0.92]
    
  4. Key Classes/Facades

    • Currency facade (primary entry point).
    • CurrencyService (service container binding).
    • RateRepository (handles data fetching/storage).

Implementation Patterns

Core Workflows

  1. Fetching Rates

    • Single Currency Pair:
      $rate = Currency::rate('USD', 'RUB'); // Returns 90.5
      
    • Bulk Rates:
      $rates = Currency::getRates('USD', ['EUR', 'GBP']); // Array of rates
      
    • Historical Rates (if supported by config):
      $historical = Currency::historical('USD', 'RUB', '2024-01-01');
      
  2. Caching

    • Configure TTL in config/currency.php:
      'cache_ttl' => 3600, // 1 hour
      'cache_driver' => 'redis', // or 'file', 'database'
      
    • Manually clear cache:
      Currency::clearCache();
      
  3. Custom Sources

    • Extend RateRepository to support custom APIs:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->bind(\BaksDev\ReferenceCurrency\Contracts\RateRepository::class, CustomRateRepository::class);
      }
      
  4. Laravel Integration

    • Service Provider Binding:
      // config/app.php
      'providers' => [
          BaksDev\ReferenceCurrency\CurrencyServiceProvider::class,
      ],
      
    • API Routes:
      Route::get('/rates/{base}', [CurrencyController::class, 'index']);
      
  5. Validation

    • Use built-in validation for currency codes:
      use BaksDev\ReferenceCurrency\Rules\ValidCurrency;
      
      $request->validate([
          'base_currency' => ['required', new ValidCurrency],
          'target_currencies' => ['array', 'required', new ValidCurrency],
      ]);
      

Gotchas and Tips

Pitfalls

  1. API Rate Limits

    • Default providers (e.g., Central Bank API) may throttle requests. Monitor logs for 429 errors.
    • Fix: Implement exponential backoff in a custom RateRepository.
  2. Timezone Mismatches

    • Historical data may return timestamps in UTC. Convert to local time:
      $localTime = now()->timezone('Europe/Moscow')->format('Y-m-d');
      
  3. Fallback Logic

    • If the primary API fails, configure fallback sources in config/currency.php:
      'sources' => [
          'primary' => 'central_bank',
          'fallback' => 'exchange_rate_api',
      ],
      
  4. Caching Issues

    • Problem: Stale cache due to manual php artisan cache:clear.
    • Fix: Use Cache::tags() to invalidate specific currency caches:
      Cache::tags(['currency-rates'])->flush();
      
  5. Currency Code Sensitivity

    • Ensure codes are uppercase (e.g., USD, not usd). Use strtoupper() if accepting user input.

Debugging

  • Enable Logging:

    'debug' => env('CURRENCY_DEBUG', false),
    

    Logs will appear in storage/logs/laravel.log.

  • Check API Responses:

    $response = Currency::getRawResponse('USD', 'RUB');
    // Inspect $response->body for raw API data.
    

Extension Points

  1. Custom Rate Sources

    • Implement BaksDev\ReferenceCurrency\Contracts\RateSource:
      class CustomSource implements RateSource {
          public function fetch(string $base, array $targets): array {
              // Your logic here
          }
      }
      
    • Register in config/currency.php:
      'sources' => [
          'custom' => \App\Services\CustomSource::class,
      ],
      
  2. Event Listeners

    • Listen for rate updates:
      // app/Listeners/LogCurrencyUpdate.php
      public function handle(CurrencyUpdated $event) {
          Log::info('Updated rate:', ['base' => $event->base, 'rates' => $event->rates]);
      }
      
  3. Testing

    • Mock the RateRepository in tests:
      $this->app->instance(
          \BaksDev\ReferenceCurrency\Contracts\RateRepository::class,
          MockRateRepository::class
      );
      

Performance Tips

  • Batch Requests: Fetch multiple currencies in a single API call where possible.
  • Lazy Loading: Use Currency::lazyRate('USD', 'RUB') to defer rate fetching until needed.
  • Database Storage: For critical apps, store rates in a currency_rates table and sync periodically:
    Currency::syncWithDatabase();
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui