youngkingoo6/laravel-amount is a Laravel package.
It currently has 0 GitHub stars and 21 downloads on Packagist (latest version v1.0.1).
Install it with composer require youngkingoo6/laravel-amount.
Discover more Laravel packages by youngkingoo6
or browse all Laravel packages to compare alternatives.
Last updated
原作者:https://github.com/hao-li/laravel-amount
系统中涉及到金额的字段,View 层表现的时候一般都是以元为单位使用小数形式展示,不过 Domain 层存储时从空间、性能、容错角度出发,经常以分为单位,用整型来存储。
在 Lavarel 中,可以在 Model 中添加属性方法进行转换
public function getAmountAttribute($value)
{
return $value / 100;
}
public function setAmountAttribute($value)
{
$this->attributes['amount'] = (int)($value * 100);
}
不过涉及金额的字段比较多时就需要定义很多相同逻辑的函数,本项目即将该逻辑抽出为 Trait,简化金额字段相关的处理。
将转换逻辑封装在 AmountTrait 中,覆写 Model 类的 getMutatedAttributes, mutateAttributeForArray, getAttributeValue 及 setAttribute 方法,当访问相关字段时自动进行转换处理。
public static $amountTimes = 100;
public function getMutatedAttributes()
{
$attributes = parent::getMutatedAttributes();
return array_merge($attributes, $this->getAmountFields());
}
protected function mutateAttributeForArray($key, $value)
{
return (in_array($key, $this->getAmountFields()))
? (function_exists('bcdiv') ? bcdiv($value, self::$amountTimes, 2) : $value / self::$amountTimes)
: parent::mutateAttributeForArray($key, $value);
}
public function getAttributeValue($key)
{
$value = parent::getAttributeValue($key);
if(function_exists('bcdiv')){
$value = bcdiv($value, self::$amountTimes,2);
}else{
$value = $value / self::$amountTimes;
}
return $value;
}
public function setAttribute($key, $value)
{
if (in_array($key, $this->getAmountFields())) {
if(function_exists('bcmul')){
$value = (int)bcmul($value, self::$amountTimes);
}else{
$value = (int)($value * self::$amountTimes);
}
}
parent::setAttribute($key, $value);
}
public function getAmountFields()
{
return (property_exists($this, 'amountFields')) ? $this->amountFields : [];
}
Laravel >= 5.2
composer require "youngkingoo6/laravel-amount:dev-master"
use Youngkingoo6\LaravelAmount\Traits\AmountTrait;
use AmountTrait;
protected $amountFields = ['amount'];
之后读取 amount 字段时,该字段的内容会自动从数据库的分转换为元,向其赋值时反之从元转换为分。
如需转换为中文金额大写,只需在模型上调用的字段后面加 '_cny' 即可返回大写金额。
$model->amount_cny;
如果不想定义 $amountFields 字段,也可以直接调用修改器
$model->cny;
以 setRawAttributes 为例(此为之前方案,目前并未覆写此方法,仅为举例,其他方法原理相同)
use AmountTrait, BTrait {
AmountTrait::setRawAttributes as amountTraitSetRawAttributes;
BTrait::setRawAttributes as BTraitSetRawAttributes;
}
public function setRawAttributes(array $attributes, $sync = false)
{
$this->BTraitSetRawAttributes($attributes, $sync);
$attributes = $this->getAttributes();
$this->amountTraitSetRawAttributes($attributes, $sync);
}
注意这里 $attributes 可能已被改变,所以再次使用时要重新取得最新值