PHP code example of v.chetkov / money

1. Go to this page and download the library: Download v.chetkov/money 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/ */

    

v.chetkov / money example snippets


 

use Chetkov\Money\Exchanger\ExchangerInterface;
use Chetkov\Money\Exchanger\RatesProvider\SimpleExchangeRatesProvider;
use Chetkov\Money\Exchanger\SimpleExchanger;

$exchangeRates = [
    'USD-RUB' => [66.34, 68.12], // Курсы покупки/продажи отличаются
    'EUR-RUB' => [72.42],        // Единый курс 
    'JPY-RUB' => [0.61],         // ...
];

return [
    'use_currency_conversation' => true,
    'exchanger_factory' => static function () use ($exchangeRates): ExchangerInterface {
        //Фабрика класса обменника
        static $instance;
        if (null === $instance) {
            $ratesProvider = SimpleExchangeRatesProvider::getInstance($exchangeRates);
            $instance = new SimpleExchanger($ratesProvider);
        }
        return $instance;
    },
];

 

use Chetkov\Money\LibConfig;

$config = 



use Chetkov\Money\Money;

$usd = Money::USD(100);
$rub = Money::RUB(200);

echo $usd->exchange(CurrencyEnum::RUB);
// Result: {"amount":6634,"currency":"RUB"}

$additionResult = $usd->add($rub);
echo $additionResult; 
// Result: {"amount":103.01,"currency":"USD"}

$subtractionResult = $rub->subtract($usd);
echo $subtractionResult; 
// Result: {"amount":-6434,"currency":"RUB"}

$multiplicationResult = $rub->multiple(5);
echo $multiplicationResult; 
// Result: {"amount":1000,"currency":"RUB"}

$evenlyAllocationResult = $usd->allocateEvenly(4);
echo json_encode($evenlyAllocationResult);
// Result: 
// [
//     {"amount":25,"currency":"USD"},
//     {"amount":25,"currency":"USD"},
//     {"amount":25,"currency":"USD"},
//     {"amount":25,"currency":"USD"}
// ]

$evenlyAllocationResult = $usd->allocateEvenly(3, 4);
echo json_encode($evenlyAllocationResult);
// Result: 
// [
//     {"amount":33.3333,"currency":"USD"},
//     {"amount":33.3333,"currency":"USD"},
//     {"amount":33.3334,"currency":"USD"}
// ]

$proportionallyAllocationResult = $usd->allocateProportionally([0.18, 0.32, 0.5, 0.3, 1]);
echo json_encode($proportionallyAllocationResult);
// Result: 
// [
//     {"amount":18,"currency":"USD"},
//     {"amount":32,"currency":"USD"},
//     {"amount":50,"currency":"USD"},
//     {"amount":30,"currency":"USD"},
//     {"amount":100,"currency":"USD"}
// ]

$rub->lessThan($usd); // true

$usd->moreThan($rub); // true

$usd->equals($rub); // false

$rub = Money::RUB(200);
$usd = Money::USD(3.015);

$isCrossCurrenciesComparison = true;
$rub->equals($usd, $isCrossCurrenciesComparison); // false

$allowableDeviationPercent = 0.5;
$rub->equals($usd, $isCrossCurrenciesComparison, $allowableDeviationPercent); // true

 

use Chetkov\Money\Exchanger\RatesProvider\CacheDecorator\ExchangeRatesProviderCacheDecorator;
use Chetkov\Money\Exchanger\RatesProvider\CacheDecorator\Strategy\ClassPropertyCacheStrategy;
use Chetkov\Money\Exchanger\RatesProvider\CbrExchangeRatesProvider;

$ratesProvider = new CbrExchangeRatesProvider();
$cacheStrategy = new ClassPropertyCacheStrategy();
$cachingDecorator = new ExchangeRatesProviderCacheDecorator($ratesProvider, $cacheStrategy, 60);

$cachingDecorator->getRates(); // Получает, кэширует и возвращает ставки от оригинального поставщика
sleep(55);
$cachingDecorator->getRates(); // Возвращает ставки из кэша
sleep(10);
$cachingDecorator->getRates(); // Получает, кэширует и возвращает ставки от оригинального поставщика

 

use Chetkov\Money\Exchanger\RatesProvider\CacheDecorator\ExchangeRatesProviderCacheDecorator;
use Chetkov\Money\Exchanger\RatesProvider\CacheDecorator\Strategy\ClassPropertyCacheStrategy;
use Chetkov\Money\Exchanger\RatesProvider\CbrExchangeRatesProvider;

$ratesProvider = new CbrExchangeRatesProvider();
$classPropertyCacheStrategy = new ClassPropertyCacheStrategy();
$redisCacheStrategy = new RedisCache();

$redisCacheDecorator = new ExchangeRatesProviderCacheDecorator($ratesProvider, $redisCacheStrategy, 3600);
$classPropertyCacheDecorator = new ExchangeRatesProviderCacheDecorator($redisCacheDecorator, $classPropertyCacheStrategy, 60);

// 1) Смотрим в кэширующем свойстве класса 
// 2) Если пусто, смотрим в редис  
// 3) Если и там пусто, идем к оригинальному провайдеру