Immutable PHP Currency Converter

Immutable PHP Currency Converter

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:

<?php

namespace Gocanto\Converter\Examples;

use Gocanto\Converter\CurrencyValue;
use Gocanto\Converter\Interfaces\CurrenciesRepositoryInterface;

class CurrenciesRepositoryExample implements CurrenciesRepositoryInterface
{
    /**
     * @param string $code
     * @return CurrencyValue
     */
    public function getCurrentRate(string $code) : CurrencyValue
    {
        // here, you need to write any related logic to query your DB. Once you have this info,
        // you will have to create the currency value object with the valid info as so:

        return new CurrencyValue('U.S. Dollars', 'USD', '$', 0.731271);
    }
}

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

use Gocanto\Converter\Examples\CurrenciesRepositoryExample;
use Gocanto\Converter\Converter;
use Gocanto\Converter\RoundedNumber;

$repository = new CurrenciesRepositoryExample;
$converter = new Converter($repository);

$conversion = $converter
    ->withAmount(RoundedNumber::make(10))
    ->withCurrency('SGD')
    ->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: News


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior Laravel Engineer
Remote okay (must already live in USA)
Hawthorne Effect
Senior Software Engineer (Remote - Contract)
Remote
Koodi Systems
PHP Developer
Pittsburgh / Remote
Sequoia Waste Solutions
Software Developer
Eindhoven
Simac IDS
Application Developer Level II (CakePHP / MySql / Vue.js)
Lancaster, PA
Harbor Compliance
FULL STACK LARAVEL DEVELOPER
LONDON - WEST END
AMPERSAND HEATLH
Mid/Senior Laravel Developer - U.S. Only
Kenner, Louisiana
Profit Miner Technologies