Immutable PHP Currency Converter

News

June 17th, 2019

laravel-money.jpg

The gocanto/converter composer package by Gustavo Ocanto is an immutable PHP currency converter that’s data-agnostic.

Related: Laravel Money is a package for formatting money in Laravel projects.

You need to bring your own database or repository of currency conversion data, and implement a data layer for the conversions. Here’s an example repository from the project:

1<?php
2
3namespace Gocanto\Converter\Examples;
4
5use Gocanto\Converter\CurrencyValue;
6use Gocanto\Converter\Interfaces\CurrenciesRepositoryInterface;
7
8class CurrenciesRepositoryExample implements CurrenciesRepositoryInterface
9{
10 /**
11 * @param string $code
12 * @return CurrencyValue
13 */
14 public function getCurrentRate(string $code) : CurrencyValue
15 {
16 // here, you need to write any related logic to query your DB. Once you have this info,
17 // you will have to create the currency value object with the valid info as so:
18
19 return new CurrencyValue('U.S. Dollars', 'USD', '$', 0.731271);
20 }
21}

Next, here’s an example of a currency conversion backed by the data repository:

1use Gocanto\Converter\Examples\CurrenciesRepositoryExample;
2use Gocanto\Converter\Converter;
3use Gocanto\Converter\RoundedNumber;
4
5$repository = new CurrenciesRepositoryExample;
6$converter = new Converter($repository);
7
8$conversion = $converter
9 ->withAmount(RoundedNumber::make(10))
10 ->withCurrency('SGD')
11 ->convertTo('USD');

You can learn more about this package, get full installation instructions, and view the source code on GitHub at gocanto/converter.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.