reaway / exchange-rate
A PHP exchange rate query library with multi-source support
v1.0.0
2026-03-28 04:08 UTC
Requires
- php: >=8.1
- ext-curl: *
- reaway/curl-client: ^1.0
- reaway/think-config: ^8.0
- reaway/think-facade: ^8.0
- reaway/think-manager: ^8.0
Requires (Dev)
- symfony/var-dumper: ^6.0
README
A PHP exchange rate query library supporting multiple data sources.
Features
- ✅ Multi-source Support — Built-in CurrencyLayer and ExchangeRate-API data sources
- ✅ Easy Extension — Simple driver extension mechanism to add new data sources
- ✅ Lazy Loading — Automatically fetches exchange rate data on first access
- ✅ Type Safe — Full PHP 8.1+ type declarations
Requirements
- PHP >= 8.1
- ext-curl
Installation
composer require reaway/exchange-rate
Usage
Basic Usage
<?php use ExchangeRate\Rate; // Configuration $config = [ 'default' => 'currency_layer', 'sources' => [ 'currency_layer' => [ 'access_key' => 'your-exchange-rate-api-key', // API访问密钥 ], 'exchange_rate_api' => [ 'access_key' => 'your-exchange-rate-api-key', // API访问密钥 ], ], ]; $rate = new Rate($config); // Get all exchange rates (based on USD) $rates = $rate->getRates('USD'); // Returns: ['EUR' => 0.92, 'CNY' => 7.23, 'JPY' => 150.45, ...] // Get specific currency exchange rate $eurRate = $rate->getRate('EUR', 'USD'); // Returns: 0.92 // Switch data source $rates = $rate->source('exchange_rate_api')->getRates('USD');
Using Facade
<?php use ExchangeRate\Facade\RateFacade; use Think\Component\Config\Facade\ConfigFacade; require dirname(__DIR__) . '/vendor/autoload.php'; // Configuration $config = [ 'default' => 'currency_layer', 'sources' => [ 'currency_layer' => [ 'access_key' => 'your-exchange-rate-api-key', // API访问密钥 ], 'exchange_rate_api' => [ 'access_key' => 'your-exchange-rate-api-key', // API访问密钥 ], ], ]; ConfigFacade::set($config, 'rate'); // Get all exchange rates $rates = RateFacade::getRates('USD'); // Get specific currency exchange rate $rate = RateFacade::getRate('EUR', 'USD');
Supported Data Sources
| Source | Website | Free Tier | Features |
|---|---|---|---|
| CurrencyLayer | currencylayer.com | ✅ | Real-time rates, 168 currencies |
| ExchangeRate-API | exchangerate-api.com | ✅ | Reliable, easy to use |
Extending Custom Data Source
Create a new driver by extending RateAbstract:
<?php namespace ExchangeRate\Source; use ExchangeRate\Abstract\RateAbstract; class MySource extends RateAbstract { protected function fetchData(): array { // Implement your API request $url = 'https://api.example.com/rates'; $response = $this->makeRequest($url); // Parse and return rates $this->rates = $response['rates']; return $response; } }
License
This project is licensed under the MIT License - see the LICENSE file for details.