PHP code example of viaaurea / currency

1. Go to this page and download the library: Download viaaurea/currency library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

viaaurea / currency example snippets


// resolve the service / get an instance
$cs = $container->get(VA\Currency\CurrencyService::class);

// create a money value object (3 equivalent ways)
$cs->create(100, 'USD');
new Money(100, 'USD');
Money::USD(100);

// exchange / conversion
$valueInUsd = Money::USD(100);
$valueInEur = $cs->exchange($valueInUsd, 'EUR');
$valueInEur->amount();

// comparison arithmetic
// < <= > >= == !=
$cs->greaterThan($valueInUsd, $valueInForeignCurrency); // or $cs->gt( ... )

// diff mixed currencies
$diff = $cs->diff($valueInEur, $valueInForeignCurrency);

// aggregate an array of Money objects with unknown or mixed currencies:
// sum, average, max or min value
$money = [ $valueInEur, $valueInUsd, $valueInForeignCurrency, ... ];
$sum = $cs->sum($money);
$max = $cs->max($money);
$min = $cs->min($money);
$avg = $cs->avg($money);

$container->register(CurrencyService::class, function(){
    $rates = [
        'EUR' => 0.9,
        'JPY' => 100,
        'AUD' => 1.5,
    ];
    $provider = new StaticExchange('USD', $rates, StaticExchange::RATE_DIRECT);
    return new CurrencyService($provider);
});

$container->register(CurrencyService::class, function(){
    $rates = [
        'USD' => 1.1,
        'JPY' => 120,
        'AUD' => 1.6,
    ];
    $provider = new StaticExchange('EUR', $rates, StaticExchange::RATE_INDIRECT);
    return new CurrencyService($provider);
});

$rates = [
    // rate for Bitcoin may be specified in micro-Bitcoins:
    'XBT' => [0.5, 0.001],
];

$cs->exchange(
    $cs->create(100, 'EUR'), 
    'USD', 
    Carbon::parse('last saturday')
);

$cs->diff(
    $cs->create(100, 'EUR'),
    $cs->create(100, 'USD'),
    Carbon::parse('2017-11-23'),
    'buy'
);

class DatabaseRateProvider implements ExchangeRateProviderInterface {

    function getExchangeRate(
        Currency $target, 
        Currency $from, 
        DateTimeInterface $at, 
        string $direction = 'middle'
    ){
        // your logic here
        // return exchange rate at a given point in time and for the specified direction
    }

}