steffenbrand / curr-curr
提供欧洲央行提供的欧元(EUR)当前汇率,以PHP对象形式交付。
4.1.0
2021-11-04 13:57 UTC
Requires
- php: ^7.3 || ^8.0
- guzzlehttp/guzzle: ^6.3
- psr/simple-cache: ^1.0
Requires (Dev)
- odan/cache: ^0.1.5
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-04 19:58:50 UTC
README
提供由欧洲央行(ECB)提供的欧元(EUR)当前汇率,以https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml下的PHP对象形式。
如何安装
composer require steffenbrand/curr-curr
如何使用
请求特定货币的汇率
try { $cc = new CurrCurr(); $exchangeRate = $cc->getExchangeRateByCurrency(Currency::USD); $exchangeRate->getDate(); $exchangeRate->getCurrency(); $exchangeRate->getRate(); } catch (ExchangeRatesRequestFailedException $e) { // webservice might not be present } catch (ExchangeRatesMappingFailedException $e) { // webservice might not deliver what we expect } catch (CurrencyNotSupportedException $e) { // requested currency might not be provided }
请求所有可用的汇率
try { $cc = new CurrCurr(); $exchangeRates = $cc->getExchangeRates(); $exchangeRates[Currency::USD]->getDate(); $exchangeRates[Currency::USD]->getCurrency(); $exchangeRates[Currency::USD]->getRate(); foreach ($exchangeRates as $exchangeRate) { $exchangeRate->getDate(); $exchangeRate->getCurrency(); $exchangeRate->getRate(); } } catch (ExchangeRatesRequestFailedException $e) { // webservice might not be present } catch (ExchangeRatesMappingFailedException $e) { // webservice might not deliver what we expect }
使用PSR-16 SimpleCache
CurrCurr不提供自己的SimpleCache实现,但它确实允许您将任何PSR-16兼容的实现注入到EcbClient中。您只需用CacheConfig实例包装它即可。
$cc = new CurrCurr( new EcbClient( EcbClient::DEFAULT_EXCHANGE_RATES_URL, new CacheConfig( new OpCache(sys_get_temp_dir() . '/cache') // Any PSR-16 compliant implementation // This example uses odan/cache ) ) );
您可以提供自己的键和生存时间。
new CacheConfig( new OpCache(sys_get_temp_dir() . '/cache') CacheConfig::CACHE_UNTIL_MIDNIGHT, // time to live in seconds CacheConfig::DEFAULT_CACHE_KEY // key used for caching );
模拟Web服务响应以进行您的项目单元测试
CurrCurr允许您注入自己的EcbClientInterface实现。但您也可以使用提供的EcbClientMock,它允许您模拟3种不同的响应。
$cc1 = new CurrCurr(new EcbClientMock(EcbClientMock::VALID_RESPONSE)); $cc2 = new CurrCurr(new EcbClientMock(EcbClientMock::USD_MISSING_RESPONSE)); $cc3 = new CurrCurr(new EcbClientMock(EcbClientMock::DATE_MISSING_RESPONSE));