Weave 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

Currex Laravel Package

older777/currex

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation
    composer require older777/currex
    
  2. Environment Setup Add these to your .env:
    CURREX_INTERVAL=60  # Auto-update interval in minutes (default: 60)
    CURREX_TIMEOUT=5    # Timeout in seconds (default: 5)
    
  3. First Usage Fetch rates in a controller or service:
    use Older777\CurrEx\Facades\CurrEx;
    
    $rates = CurrEx::getRates(); // Returns associative array of USD to [currency] rates
    $eurRate = $rates['EUR'];    // Example: 0.85
    

Where to Look First

  • Facade: Older777\CurrEx\Facades\CurrEx (primary entry point).
  • Config: config/currex.php (if published via php artisan vendor:publish).
  • Cache: Check storage/framework/cache/ for cached XML feeds.

Implementation Patterns

Core Workflows

  1. Fetching Rates

    // Get all rates
    $allRates = CurrEx::getRates();
    
    // Get specific currency rate
    $gbpRate = CurrEx::getRate('GBP');
    
    // Force refresh (bypasses cache)
    $freshRates = CurrEx::refreshRates();
    
  2. Caching & Auto-Update

    • Rates auto-update every CURREX_INTERVAL minutes (default: 60).
    • Cache is stored as a serialized array in Laravel’s cache system.
    • Manual Refresh: Call CurrEx::refreshRates() to force an update.
  3. Error Handling

    • Silent mode enabled by default (suppresses Guzzle exceptions).
    • Check for failures:
      if (CurrEx::hasError()) {
          $error = CurrEx::getError();
      }
      
  4. Integration with Models

    // Example: Convert USD to EUR in a Product model
    public function getPriceInEur()
    {
        return $this->price * CurrEx::getRate('EUR');
    }
    
  5. Custom Rounding

    • Rates are rounded to 2 decimal places by default.
    • Override in config:
      'rounding' => 4, // Custom precision
      

Advanced Patterns

  • Rate Validation:
    if (!CurrEx::isRateAvailable('XYZ')) {
        // Fallback logic or throw custom exception
    }
    
  • Batch Processing:
    $currencies = ['EUR', 'GBP', 'JPY'];
    $batchRates = CurrEx::getRates($currencies); // Returns subset
    
  • Rate History: Combine with Laravel’s cache tags or a custom table to log historical rates.

Gotchas and Tips

Pitfalls

  1. Deprecated Laravel Versions

    • Only supports Laravel 5.0–5.7. Do not use with Laravel 8+ without forking.
    • Fix: Use a wrapper or polyfill for newer Laravel versions (e.g., illuminate/cache for caching).
  2. Cache Staleness

    • If CURREX_INTERVAL is too long (e.g., 1440 minutes), rates may become outdated.
    • Tip: Set CURREX_INTERVAL=60 for hourly updates in production.
  3. XML Feed Failures

    • FloatRates.com may block requests or return malformed XML.
    • Debugging:
      CurrEx::setSilentMode(false); // Enable exceptions
      try {
          $rates = CurrEx::getRates();
      } catch (\Exception $e) {
          // Log $e->getMessage()
      }
      
  4. Currency Code Sensitivity

    • Case-sensitive: 'eur' ≠ 'EUR'. Always use uppercase (e.g., 'USD').
    • Unsupported Currencies: Returns null for unsupported codes (e.g., 'XYZ').
  5. Timeout Issues

    • High CURREX_TIMEOUT may cause delays; low values risk partial data.
    • Recommendation: Keep CURREX_TIMEOUT=5 unless debugging.

Tips

  1. Publish Config

    php artisan vendor:publish --provider="Older777\CurrEx\CurrExServiceProvider"
    
    • Customize config/currex.php for rounding, silent mode, or cache drivers.
  2. Cache Driver

    • Defaults to Laravel’s default cache driver (e.g., file, redis).
    • Tip: Use redis for distributed caching in multi-server setups.
  3. Testing

    • Mock the facade in tests:
      $this->app->instance(\Older777\CurrEx\Facades\CurrEx::class, $mockCurrEx);
      
    • Use CurrEx::shouldReturn([]) to simulate empty rates.
  4. Rate Conversion Utility Create a helper trait:

    trait Convertible
    {
        public function convertTo(string $targetCurrency, float $amount): float
        {
            $usdRate = CurrEx::getRate($targetCurrency);
            return $amount * $usdRate;
        }
    }
    
  5. Fallback Rates Store default rates in config for offline use:

    'fallback_rates' => [
        'EUR' => 0.85,
        'GBP' => 0.75,
    ],
    

    Then extend the package or override getRate() logic.

  6. Logging Add logging for rate updates:

    CurrEx::setLogger(function ($message) {
        \Log::info($message, ['package' => 'currex']);
    });
    
  7. Performance

    • Avoid calling getRates() in loops. Cache results in memory or Redis.
    • Example:
      $rates = CurrEx::getRates();
      foreach ($products as $product) {
          $product->eurPrice = $product->usdPrice * $rates['EUR'];
      }
      
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.
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels