一个用于处理金钱的简单包。
A simple package for working with money.
Main features:
This package is our implementation of the Money pattern.
You can read more about why we built it and how it works on our forum: New package: archtechx/money.
Require the package via composer:
composer require archtechx/moneyThe package has two main classes:
Money which represents monetary valuesCurrency which is extended by the currencies that you're usingThis document uses the terms decimal value, base value, default currency, current currency, rounding, math decimals, display decimals, and a few others. Refer to the Terminology section for definitions.
Important: As an implementation of the Money pattern, the Money object creates a new instance after each operation. Meaning, all Money instances are immutable. To modify the value of a variable, re-initialize it with a new value:
// Incorrect
$money = money(1500);
$money->times(3); // ❌
$money->value(); // 1500
// Correct
$money = money(1500);
$money = $money->times(3); // ✅
$money->value(); // 4500Money instances// Using cents
$money = money(1500); // $15.00; default currency
$money = money(1500, 'EUR'); // 15.00 €
$money = money(2000, new USD); // $20.00
$money = money(3000, CZK::class); // 30 Kč
// Using decimals
$money = Money::fromDecimal(15.00, 'EUR'); // 15.00 €
$money = Money::fromDecimal(20.00, new USD); // $20.00
$money = Money::fromDecimal(30.00, CZK::class); // 30 Kč// Addition
$money = money(1000);
$money = $money->add(500);
$money->value(); // 1500
// Subtraction
$money = money(1000);
$money = $money->subtract(500);
$money->value(); // 500
// Multiplication
$money = money(1000);
$money = $money->multiplyBy(2); // alias: ->times()
$money->value(); // 2000
// Division
$money = money(1000);
$money = $money->divideBy(2);
$money->value(); // 500$money = money(2200);
$money->convertTo(CZK::class);Equality of monetary value
// Assuming CZK is 25:1 USD
// ✅ true
money(100, USD::class)->equals(money(100, USD::class));
// ❌ false
money(100, USD::class)->equals(money(200, USD::class));
// ✅ true
money(100, USD::class)->equals(money(2500, CZK::class));
// ❌ false
money(100, USD::class)->equals(money(200, CZK::class));Equality of monetary value AND currency
// Assuming CZK is 25:1 USD
// ✅ true
money(100, USD::class)->is(money(100, USD::class));
// ❌ false: different monetary value
money(100, USD::class)->is(money(200, USD::class));
// ❌ false: different currency
money(100, USD::class)->is(money(2500, CZK::class));
// ❌ false: different currency AND monetary value
money(100, USD::class)->is(money(200, CZK::class));You can use the addFee() or addTax() methods to add a % fee to the money:
$money = money(1000);
$money = $money->addTax(20.0); // 20%
$money->value(); // 1200$money = Money::fromDecimal(100.0, new USD);
$money->value(); // 10000
$money->decimal(); // 100.0You can format money using the ->formatted() method. It takes display decimals into consideration.
$money = Money::fromDecimal(40.25, USD::class);
$money->formatted(); // $40.25The method optionally accepts overrides for the currency specification:
$money = Money::fromDecimal(40.25, USD::class);
// $ 40.25 USD
$money->formatted(decimalSeparator: ',', prefix: '$ ', suffix: ' USD');The overrides can also be passed as an array:
$money = Money::fromDecimal(40.25, USD::class);
// $ 40.25 USD
$money->formatted(['decimalSeparator' => ',', 'prefix' => '$ ', 'suffix' => ' USD']);There's also ->rawFormatted() if you wish to use math decimals instead of display decimals.
$money = Money::new(123456, CZK::class);
$money->rawFormatted(); // 1 234,56 KčConverting the formatted value back to the Money instance is also possible. The package tries to extract the currency from the provided string:
$money = money(1000);
$formatted = $money->formatted(); // $10.00
$fromFormatted = Money::fromFormatted($formatted);
$fromFormatted->is($money); // trueIf you had passed overrides while formatting the money instance, the same can passed to this method.
$money = money(1000);
$formatted = $money->formatted(['prefix' => '$ ', 'suffix' => ' USD']); // $ 10.00 USD
$fromFormatted = Money::fromFormatted($formatted, USD::class, ['prefix' => '$ ', 'suffix' => ' USD']);
$fromFormatted->is($money); // trueNotes:
fromFormatted() misses the cents if the math decimals are greater than display decimals.Some currencies, such as the Czech Crown (CZK), generally display final prices in full crowns, but use cents for the intermediate math operations. For example:
$money = Money::fromDecimal(3.30, CZK::class);
$money->value(); // 330
$money->formatted(); // 3 Kč
$money = $money->times(3);
$money->value(); // 990
$money->formatted(); // 10 KčIf the customer purchases a single 3.30 item, he pays 3 CZK, but if he purchases three 3.30 items, he pays 10 CZK.
This rounding (to full crowns) is standard and legal per the accounting legislation, since it makes payments easier. However, the law requires you to keep track of the rounding difference for tax purposes.
For that use case, our package lets you get the rounding difference using a simple method call:
$money = Money::fromDecimal(9.90, CZK::class);
$money->decimal(); // 9.90
$money->formatted(); // 10 Kč
$money->rounding(); // +0.10 Kč = 10
$money = Money::fromDecimal(3.30, CZK::class);
$money->decimal(); // 3.30
$money->formatted(); // 3 Kč
$money->rounding(); // -0.30 Kč = -30// Using the currency rounding
$money = Money::fromDecimal(9.90, CZK::class);
$money->decimal(); // 9.90
$money = $money->rounded(); // currency rounding
$money->decimal(); // 10.0
// Using custom rounding
$money = Money::fromDecimal(2.22, USD::class);
$money->decimal(); // 2.22
$money = $money->rounded(1); // custom rounding: 1 decimal
$money->decimal(); // 2.20To work with the registered currencies, use the bound CurrencyManager instance, accessible using the currencies() helper.
This package provides only USD currency by default.
You can create a currency using one of the multiple supported syntaxes.
// anonymous Currency object
$currency = new Currency(
code: 'FOO',
name: 'Foo currency',
rate: 1.8,
prefix: '# ',
suffix: ' FOO',
);
// array
$currency = [
'code' => 'FOO',
'name' => 'Foo currency',
'rate' => 1.8,
'prefix' => '# ',
'suffix' => ' FOO',
];
// class
class FOO extends Currency
{
protected string $code = 'FOO';
protected string $name = 'Foo currency';
protected float $rate = 1.8;
protected string $prefix = '# ';
protected string $suffix = ' FOO';
}See the Currency logic section for a list of available properties to configure. Note that when registering a currency, two values must be specified:
USD)United States Dollar)Register a new currency:
currencies()->add(new USD);
currencies()->add(USD::class);
currencies()->add($currency); // object or arrayTo remove a specific currency, you can use the remove() method:
currencies()->remove('USD');
currencies()->remove(USD::class);To remove all currencies, you can use the clear() method:
currencies()->clear();Can be useful in tests. This reverts all your changes and makes the CurrencyManager use USD as the default currency.
currencies()->reset();Currencies can have the following properties:
protected string $code = null;
protected string $name = null;
protected float $rate = null;
protected string $prefix = null;
protected string $suffix = null;
protected int $mathDecimals = null;
protected int $displayDecimals = null;
protected int $rounding = null;
protected string $decimalSeparator = null;
protected string $thousandsSeparator = null;For each one, there's also a public method. Specifying a method can be useful when your currency config is dynamic, e.g. when the currency rate is taken from some API:
public function rate(): float
{
return cache()->remember("{$this->code}.rate", 3600, function () {
return Http::get("https://api.currency.service/rate/USD/{$this->code}");
});
}You can set the default currency using the setDefault() method:
currencies()->setDefault('USD');You can set the current currency using the setCurrent() method:
currencies()->setCurrent('USD');If your users can select the currency they want to see the app in, the package can automatically write the current currency to a persistent store of your choice, and read from that store on subsequent requests.
For example, say we want to use the currency session key to keep track of the user's selected session. To implement that, we only need to do this:
currencies()
->storeCurrentUsing(fn (string $code) => session()->put('currency', $code))
->resolveCurrentUsing(fn () => session()->get('currency'));You can add this code to your AppServiceProvider's boot() method.
Now, whenever the current currency is changed using currencies()->setCurrent(), perhaps in a route like this:
Route::get('/currency/change/{currency}', function (string $currency) {
currencies()->setCurrent($currency);
return redirect()->back();
});it will also be written to the currency session key. The route can be used by a `` in your navbar, or any other UI element.
This section explains the terminology used in the package.
Multiple different things can be meant by the "value" of a Money object. For that reason, we use separate terms.
The base value is the value passed to the money() helper:
$money = money(1000);and returned from the ->value() method:
$money->value(); // 1000This is the actual integer value of the money. In most currencies this will be the cents.
The package uses the base value for all money calculations.
The decimal value isn't used for calculations, but it is the human-readable one. It's typically used in the formatted value.
$money = Money::fromDecimal(100.0); // $100 USD
$money->value(); // 10000
$money->decimal(); // 100.0This is the value of a Money object converted to the default curre
暂无开放 Issues,或尚未同步最近议题。