PHP code example of adsmurai / currency

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

    

adsmurai / currency example snippets




use Adsmurai\Currency\Contracts\Currency;
use Adsmurai\Currency\CurrencyFactory;
use Adsmurai\Currency\MoneyFactoriesLocator;
use Adsmurai\Currency\MoneyFactory;

// This factory will create Currency objects given the currency ISO code.
// By default, it will load the currency data from a library's internal data
// source, but we can use alternative data sources.
$currencyFactory = CurrencyFactory::fromDataPath();
$currencyFactory = CurrencyFactory::fromDataArray([
    'EUR' => [
        'numFractionalDigits' => 2,
        'symbol' => '€',
        'symbolPlacement' => Currency::AFTER_PLACEMENT,
    ],
    'USD' => [
        'numFractionalDigits' => 2,
        'symbol' => '$',
        'symbolPlacement' => Currency::BEFORE_PLACEMENT,
    ]
]);

// This factory will create Money objects with the same currency type.
// The rationale behind this class is that almost always we'll work with the
// same currency type.
$moneyFactory = new MoneyFactory(
    $currencyFactory->buildFromISOCode('EUR')
);

// In fact, to avoid introducing hard dependencies on the factory implementation
// through the instantiation (via the `new` operator), we recommend to obtain
// the `MoneyFactory` instances through the `MoneyFactoriesLocator`.
//
// This will have some advantages:
//   * We can inject instances of the `MoneyFactoriesLocator` contract in our
//     domain logic without having to rely on specific implementations.
//   * We can avoid `MoneyFactory` instances proliferation, since this
//     factories locator keeps one single instances per currency ISO code.
$moneyFactoriesLocator = new MoneyFactoriesLocator($currencyFactory);
$moneyFactory = $moneyFactoriesLocator->getMoneyFactory('EUR');

// We have many ways to construct Money objects, depending on the data we
// have at the time.
$money = $moneyFactory->buildFromString('10.57');
$money = $moneyFactory->buildFromString('10.57€'); // Look! it will validate the symbol too :)
$money = $moneyFactory->buildFromString('10.57 €');
$money = $moneyFactory->buildFromString('10.57EUR'); // Look! it will validate the ISO code too :)
$money = $moneyFactory->buildFromString('10.57 EUR');
$money = $moneyFactory->buildFromFloat(10.57);
$money = $moneyFactory->buildFromFractionalUnits(1057);

// If we want to format a currency value, we can use a specific method, that
// will take into account the number of digits, symbol, symbol placement...
echo $money->format();