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

Fx Rate Bundle Laravel Package

boonkuaeboonsutta/fx-rate-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require boonkuaeboonsutta/fx-rate-bundle
    
  2. Configure Routes Create config/routes/bk_fx_rate.yml:

    _bk_fx_rate:
        resource: '@BKFxRateBundle/Resources/config/routes.xml'
        prefix: /api/fxrate/
    
  3. Configure API Endpoint Create config/packages/bk_fx_rate.yml:

    bk_fx_rate:
        endpoints: https://forex.1forge.com/1.0.3/convert
        api_key: 'your_api_key_here'
    
  4. First Use Case Inject the service in a controller or service:

    use BK\FxRateBundle\Service\FxRateService;
    
    class CurrencyController extends Controller
    {
        public function __construct(private FxRateService $fxRateService) {}
    
        public function convert(Request $request)
        {
            $amount = $request->input('amount');
            $from = $request->input('from');
            $to = $request->input('to');
    
            $result = $this->fxRateService->convert($amount, $from, $to);
            return response()->json($result);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Currency Conversion Use the convert() method to fetch real-time exchange rates:

    $rate = $this->fxRateService->convert(100, 'USD', 'EUR');
    
  2. Dependency Injection Autowire FxRateService in any class where currency conversion is needed:

    public function __construct(private FxRateService $fxRateService) {}
    
  3. API Integration Extend the service to handle additional endpoints or custom logic:

    $this->fxRateService->setEndpoint('https://custom-api.com/convert');
    
  4. Caching (Manual) Cache responses to avoid repeated API calls (not built-in; implement via Laravel Cache):

    $cacheKey = "fxrate_{$from}_{$to}";
    $rate = Cache::remember($cacheKey, now()->addHours(1), function () use ($fxRateService, $amount, $from, $to) {
        return $fxRateService->convert($amount, $from, $to);
    });
    

Integration Tips

  • Validation: Validate API responses before processing (e.g., check for success flag or error fields).
  • Error Handling: Wrap API calls in try-catch blocks to handle HTTP/rate-limit errors:
    try {
        $rate = $this->fxRateService->convert($amount, $from, $to);
    } catch (\Exception $e) {
        Log::error("FX Rate API Error: " . $e->getMessage());
        return response()->json(['error' => 'Service unavailable'], 503);
    }
    
  • Testing: Mock FxRateService in unit tests:
    $this->mock(FxRateService::class)->shouldReceive('convert')->andReturn(['rate' => 0.85]);
    

Gotchas and Tips

Pitfalls

  1. Deprecated API The underlying forex.1forge.com API may be outdated or discontinued. Verify endpoint availability before production use.

  2. No Built-in Caching The bundle does not cache responses by default. Implement caching manually (e.g., Laravel Cache, Redis) to avoid hitting API rate limits.

  3. Hardcoded Endpoint The endpoints config key is singular, implying only one API can be configured. For multi-provider support, extend the service or use a facade pattern.

  4. No Type Safety API responses are likely returned as raw arrays. Validate and cast responses to typed objects (e.g., FxRateResponse) for safer usage:

    class FxRateResponse {
        public function __construct(
            public float $rate,
            public string $from,
            public string $to,
            public float $amount
        ) {}
    }
    
  5. Rate Limiting The API may throttle requests. Monitor HTTP status codes (e.g., 429) and implement retries with exponential backoff.

Debugging

  • Log API Responses Override the service to log raw responses for debugging:
    $this->fxRateService->setLogger(function ($response) {
        Log::debug('FX Rate API Response', ['response' => $response]);
    });
    
  • Check HTTP Headers Ensure the api_key is correctly passed in headers (if required by the API). The bundle may not handle this automatically.

Extension Points

  1. Custom Providers Extend FxRateService to support multiple APIs:

    class MultiFxRateService extends FxRateService {
        public function convertWithProvider(string $provider, float $amount, string $from, string $to) {
            $this->setEndpoint($this->getProviderEndpoint($provider));
            return parent::convert($amount, $from, $to);
        }
    }
    
  2. Webhook Support Add a listener to update exchange rates via webhooks (e.g., from a financial provider):

    Event::listen('fxrate.updated', function ($rate) {
        Cache::put("fxrate_{$rate->from}_{$rate->to}", $rate->rate, now()->addHours(1));
    });
    
  3. Fallback Mechanism Implement a fallback to a secondary API if the primary fails:

    try {
        return $this->fxRateService->convert($amount, $from, $to);
    } catch (\Exception $e) {
        $this->fxRateService->setEndpoint('https://fallback-api.com/convert');
        return $this->fxRateService->convert($amount, $from, $to);
    }
    

Config Quirks

  • Case Sensitivity Ensure bk_fx_rate in config/packages/bk_fx_rate.yml matches the bundle’s namespace (BK\FxRateBundle).
  • Environment Variables Store the api_key in .env and reference it in the config:
    bk_fx_rate:
        api_key: '%env(FX_RATE_API_KEY)%'
    
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.
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
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope