desmart / laravel-money
轻松管理Laravel中的货币
Requires
- php: ^7.4|^8.0
- illuminate/database: ^8.12
- moneyphp/money: ^3.3
Requires (Dev)
- orchestra/testbench: ^6.0
- phpunit/phpunit: ^9.3.3
This package is auto-updated.
Last update: 2024-09-18 15:04:09 UTC
README
该包提供对 \Money\Money
对象创建和格式化的简单封装。
最低Laravel版本是 8.12.0
安装
要使用Composer安装此包,请运行以下命令
composer require desmart/laravel-money
用法
该包提供三个主要元素
- 货币对象工厂,
- 货币对象格式化器,
- 货币对象类型转换类。
工厂
工厂简化了 \Money\Money
对象的实例化。可以使用整数或浮点值创建 \Money\Money
对象。
\DeSmart\Larvel\Money\MoneyFactory::fromInteger(1000); // New object with the lowest subunit of the (default) currency \DeSmart\Larvel\Money\MoneyFactory::fromInteger(1000, 'PLN'); // New object with specified currency
\DeSmart\Larvel\Money\MoneyFactory::fromFloat(10); // New object with 'regular' unit of the (default) currency, i.e. 10.50 USD means 10 dollars and 50 cents \DeSmart\Larvel\Money\MoneyFactory::fromFloat(10, 'PLN') // New object with specified currency
默认货币
如果应用程序不处理多种货币,建议将默认货币设置为所需的货币。这可以加快编码并减少错误。默认货币可以非常容易地设置
// For example, in AppServiceProvider.php \DeSmart\Larvel\Money\MoneyFactory::$defaultCurrency = 'USD'; // Package's default is set to 'EUR'
格式化器
要格式化货币值,请调用 \DeSmart\Larvel\Money\MoneyFormatter::prettyPrint($money)
。 prettyPrint
方法还接受一个可选参数,表示格式化的值是否应包含HTML实体 - 实际上,格式化值中的每个空格都将替换为  
。
\DeSmart\Larvel\Money\MoneyFormatter
在幕后使用已注册的格式化器类。如果没有注册自定义类,则默认使用 \Money\Formatter\DecimalMoneyFormatter
格式化器。
该包还包含一个额外的格式化器,\DeSmart\Larvel\Money\Formatters\IntlDecimalMoneyFormatter
,允许定义特定的格式来呈现货币值。有一些默认值(作为常量)
- 仅显示金额(
{AMOUNT}
), - 显示货币代码和金额(
{CURRENCY}{AMOUNT}
), - 显示货币代码和金额,用空格分隔(
{CURRENCY}{SPACE}{AMOUNT}
), - 显示金额和货币代码(
{AMOUNT}{CURRENCY}
), - 显示金额和货币代码,用空格分隔(
{AMOUNT}{SPACE}{CURRENCY}
)。 - 显示货币符号和金额(
{CURRENCY_SYMBOL}{AMOUNT}
), - 显示货币符号和金额,用空格分隔(
{CURRENCY_SYMBOL}{SPACE}{AMOUNT}
), - 显示金额和货币符号(
{AMOUNT}{CURRENCY_SYMBOL}
), - 显示金额和货币符号,用空格分隔(
{AMOUNT}{SPACE}{CURRENCY_SYMBOL}
)。
可以使用任何其他格式,只要它利用四个关键字: {AMOUNT}
、{CURRENCY}
、{CURRENCY_SYMBOL}
、{SPACE}
。除了格式外,还可以定义小数点和千位分隔符。
注册格式化器相对简单
// For example, in AppServiceProvider.php \DeSmart\Larvel\Money\MoneyFormatter::formatUsing( new \DeSmart\Larvel\Money\Formatters\IntlDecimalMoneyFormatter('{AMOUNT}{CURRENCY}', ',', ' ') );
感谢 PruvoNet/price-extractor 提供货币符号列表。
Laravel模型属性转换
该包还提供了一个自定义转换类,允许在Laravel模型中使用 \Money\Money
对象。
protected $casts = [ 'money' => \DeSmart\Larvel\Money\Casts\Money::class, ];
默认情况下,在将值转换为货币对象时,将使用模型的 currency
属性作为货币(如果没有在模型中设置 currency
属性,则使用应用程序的默认货币)。如果需要从自定义属性名中获取货币,可以在模型的 $casts
数组中定义此类属性,如下所示
protected $casts = [ 'money' => \DeSmart\Larvel\Money\Casts\Money::class . ':my_custom_currency_attribute', ];
转换类从模型获取/设置类似货币的值,并且还有一个方法用于将 \Money\Money
对象序列化为数组(当在模型上使用 toArray
或 toJson
方法时)
[ // ... 'money' => [ 'amount' => '10000', 'currency' => 'PLN', 'formatted' = '100,00 PLN', 'float' = 100.0 ], ]
更新日志
请参阅 CHANGELOG 以获取有关最近更改的更多信息。
许可证
麻省理工学院许可证(MIT)。请参阅许可文件以获取更多信息。