chrgriffin/eloquent-moneyphp

自动将 Eloquent 列转换为 MoneyPHP 对象。

1.1.1 2020-10-28 17:54 UTC

This package is auto-updated.

Last update: 2024-08-29 02:30:29 UTC


README

Build Status Coverage Status License

Eloquent-MoneyPHP

自动将 Eloquent 列转换为 MoneyPHP 对象。

安装

使用 composer 安装 Eloquent-MoneyPHP

composer install chrgriffin/eloquent-moneyphp

要求

  • PHP >= 7.1.3
  • Laravel >= 5.6

此包的一个关键假设是:您在数据库中以整数形式存储货币,而不是浮点值。例如,80美元将存储为800,而不是8.00。要了解为什么您应该以这种方式存储货币和其他浮点值,请阅读关于经典问题的说明这里

使用方法

使用方法非常简单。Eloquent-MoneyPHP 提供了一个特性,可以在任何 Eloquent 模型上使用,并结合一列列名数组

<?php

namespace App;

use EloquentMoneyPHP\HasCurrency;

class MyModel extends Model
{
    use HasCurrency;
    
    protected $currencies = [
        'total_usd' => 'USD',
        'total_eur' => 'EUR'
    ];
}

在上面的设置中,访问 total_usdtotal_eur 属性将自动将属性转换为 MoneyPHP 对象

<?php

$model = MyModel::find(1);
$total = $model->total_usd; // <-- this will return a MoneyPHP object

Eloquent-MoneyPHP 还支持将货币金额作为 json 字符串存储在文本列中。

"{\"amount\": 800,\"currency\": \"USD\"}"

然后适当配置您的模型

<?php

namespace App;

use EloquentMoneyPHP\HasCurrency;

class MyModel extends Model
{
    use HasCurrency;
    
    protected $currencies = [
        'total' => 'json'
    ];
}

内部机制

Eloquent-MoneyPHP 利用 Laravel 的魔法方法 getAttribute()setAttribute(),结合配置的列名数组,以确定是否应将给定属性转换为 MoneyPHP 对象。

如果您自己实现了 getAttribute()setAttribute(),这显然可能会造成问题。幸运的是,如果您需要,您可以在自己的方法中包含包的行为。

<?php

namespace App;

use EloquentMoneyPHP\HasCurrency;

class MyModel extends Model
{
    use HasCurrency;
    
    protected $currencies = [
        'total' => 'json'
    ];
    
    public function getAttribute($key)
    {
        if($this->attributeIsMoney($key)) {
            return $this->getMoneyAttribute($key);
        }

        // the rest of your logic
    }
        
    public function setAttribute($key, $value)
    {
        if($this->attributeIsMoney($key)) {
            return $this->setMoneyAttribute($key, $value);
        }

        // the rest of your logic
    }
}