Flourish PHP Unframework
This is an archived copy of the forum for reference purposes

Adding live and/or historic exchange rates to flourishlib's fMoney class.

posted by netcarver 7 years ago

Flourish is a great library but I find the conversion between currencies using fMoney somewhat limiting. I've worked up an few extension classes that build on Flourish's fMoney foundation and add live and/or historic exchange rate support courtesy of Joss Crowcroft's http://openexchangerates.org project.

My extension adds an interface (fxCurrencyExchange), a concrete implementation for openexchangerates.org (fxOpenExchangeRateCurrencyExchange) an extension to fMoney (fxMoney) to allow simplified conversion and a convenience class for handling leap years (fxYear.)

Basic usage is the same as fMoney...

fxMoney::setDefaultCurrency('USD');
$usd = new fxMoney( '100' ); // Create a USD amount.
fxMoney::defineCurrency( 'GBP', 'Pound Sterling', '', 2 ); // Define a new currency, 'GBP' (Pound Sterling) -- use ISO 4217 three-letter codes.

But, you can now specify a currency exchange (and, if needed, an exchange rate cache using flourish's fCache)...

$currency_cache = new fCache(...); // Setup an fCache for currency values as required. Using a non-volatile cache is probably a good idea here.
$exchange = new fxOpenExchangeRateCurrencyExchange( $currency_cache ); // Setup an exchange
fxMoney::setCurrencyExchange( $exchange );  // Tells fxMoney to use this as its exchange.

You can now use fxMoney to convert using live exchange rates...

$gbp = $usd->toGBP(); // Convert to GBP using the live exchange rate from OpenExchangeRates.org at the time of call.

... or fixed exchange rates...

$gbp = $usd->toGBP('0.65'); // Conversion done using a fixed exchange rate between the two currencies : GBP = 0.65 * USD.

... or some historical exchange rate if you give it a date...

$gbp = $usd->toGBP( '2011-01-31' ); // Conversion done using historical market rate. The historical data will be cached if a cache is defined.

Code is available from https://gist.github.com/fc8b9fd41e66cb36af2c if you want to try this out. Feedback welcome here or on the github page.