ph-il/money-bundle

这是一个集成 moneyphp/money 库(Fowler 模式)的 Symfony 扩展包:https://github.com/moneyphp/money。

安装1,410

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 0

分支: 74

开放问题: 0

类型:symfony-bundle

v6.3.3 2023-12-19 21:48 UTC

README

Build Status PHP Symfony Downloads Latest Stable Version license

此扩展包用于将 mathiasverraes 的 Money 库 集成到 Symfony 项目中。

此扩展包是基于 TbbcMoneyBundle 的分支。

此库基于 Fowler 的 Money 模式

  • 此扩展包经过测试,与 Symfony 6.3+ 和 7 稳定兼容

快速开始

use Money\Money;
use Phil\MoneyBundle\Form\Type\MoneyType;

// the money library
$fiveEur = Money::EUR(500);
$tenEur = $fiveEur->add($fiveEur);
list($part1, $part2, $part3) = $tenEur->allocate(array(1, 1, 1));
assert($part1->equals(Money::EUR(334)));
assert($part2->equals(Money::EUR(333)));
assert($part3->equals(Money::EUR(333)));

// a service that stores conversion ratios
$pairManager = $this->get('phil_money.pair_manager');
$usd = $pairManager->convert($tenEur, 'USD');

// a form integration
$formBuilder->add('price', MoneyType::class);

功能

  • 集成 mathiasverraes 的 Money 库
  • 在模板中提供货币和货币的 Twig 过滤器和 PHP 辅助函数
  • 货币比率存储系统
  • 从外部 API 获取比率的 ratioProvider 系统
  • Symfony 表单集成
  • 不同操作的控制台命令
  • 用于指定网站使用的货币的配置解析器
  • 访问获取的货币比率的记录
  • Money 格式化国际化

目录

安装

使用 Composer 安装:
$ composer require phil/money-bundle

对于 Symfony 6 及以上版本,将扩展包添加到 config/bundles.php(如果安装包时未自动添加)

    return [
        // ...
        Phil\MoneyBundle\PhilMoneyBundle::class => ['all' => true],
    ];

创建一个类似于 config/packages/phil_money.yml 的文件并将其添加到其中。

phil_money:
    currencies: ["USD", "EUR"]
    reference_currency: "EUR"
    decimals: 2

在您的 config.yml 或 config/packages/phil_money.yml 中添加表单字段表示

twig:
    form_themes:
        - '@PhilMoney/Form/fields.html.twig'

您还应注册自定义 Doctrine Money 类型

doctrine:
    dbal:
        types:
            money: Phil\MoneyBundle\Type\MoneyType

使用

Money 库集成

use Money\Money;

$fiveEur = Money::EUR(500);
$tenEur = $fiveEur->add($fiveEur);
list($part1, $part2, $part3) = $tenEur->allocate(array(1, 1, 1));
assert($part1->equals(Money::EUR(334)));
assert($part2->equals(Money::EUR(333)));
assert($part3->equals(Money::EUR(333)));

$pair = new CurrencyPair(new Currency('EUR'), new Currency('USD'), 1.2500);
$usd = $pair->convert($tenEur);
$this->assertEquals(Money::USD(1250), $usd);

表单集成

您有 3 种新的表单类型(位于 Phil\MoneyBundle\Form\Type 命名空间下)

  • CurrencyType : 从在 config.yml 中定义的货币中选择货币
  • MoneyType : 请求金额和货币
  • SimpleMoneyType : 请求金额并将货币设置为 config.yml 中设置的参考货币

示例

use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

// I create my form
$form = $this->createFormBuilder()
    ->add('name', TextType::class)
    ->add('price', MoneyType::class, [
        'data' => Money::EUR(1000), //EUR 10
    ])
    ->add('save', SubmitType::class)
    ->getForm();

操作表单

使用 MoneyType,您可以使用以下方式操作表单元素:

amount_options 用于金额字段,以及 currency_options 用于货币字段,例如如果您想更改标签。

$form = $this->createFormBuilder()
    ->add('price', MoneyType::class, [
        'data' => Money::EUR(1000), //EUR 10
        'amount_options' => array(
            'label' => 'Amount',
        ),
        'currency_options' => array(
            'label' => 'Currency',
        ),
    ])
    ->getForm();

使用 CurrencyType 只能使用 currency_options,而使用 SimpleMoneyType 只能使用 amount_options

使用 Doctrine 保存货币

解决方案 1:数据库中的两个字段

请注意,DB 表中有 2 列:$priceAmount 和 $priceCurrency,以及一个 getter/setter:getPrice 和 setPrice。

get/setPrice 方法会透明地处理这两个列。

  • 优点:您的数据库清洁,您可以在数据库中使用两个不同列的金额和货币执行 sql sum、group by、sort 等。
  • 缺点:在实体中看起来很丑。
<?php
namespace App\AdministratorBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Money\Currency;
use Money\Money;

/**
 * TestMoney
 *
 * @ORM\Table("test_money")
 * @ORM\Entity
 */
class TestMoney
{
    /**
     * @var integer
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="price_amount", type="integer")
     */
    private $priceAmount;

    /**
     * @var string
     *
     * @ORM\Column(name="price_currency", type="string", length=64)
     */
    private $priceCurrency;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * get Money
     *
     * @return Money
     */
    public function getPrice()
    {
        if (!$this->priceCurrency) {
            return null;
        }
        if (!$this->priceAmount) {
            return new Money(0, new Currency($this->priceCurrency));
        }
        return new Money($this->priceAmount, new Currency($this->priceCurrency));
    }

    /**
     * Set price
     *
     * @param Money $price
     * @return TestMoney
     */
    public function setPrice(Money $price)
    {
        $this->priceAmount = $price->getAmount();
        $this->priceCurrency = $price->getCurrency()->getCode();

        return $this;
    }
}

解决方案 2:使用 Doctrine 类型

您的 DB 表中只有一个字符串列。money 对象由新的 Doctrine 类型手动序列化。

1.25€ 在您的数据库中被序列化为 'EUR 125'。 此格式是稳定的。它不会在未来版本中更改。

新的 Doctrine 类型名称是 "money"。

  • 优点:实体易于创建和使用
  • 缺点:直接在 SQL 中请求数据库更困难。
<?php
namespace App\AdministratorBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Money\Money;

/**
 * TestMoney
 *
 * @ORM\Table("test_money")
 * @ORM\Entity
 */
class TestMoney
{
    /**
     * @var integer
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var Money
     *
     * @ORM\Column(name="price", type="money")
     */
    private $price;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * get Money
     *
     * @return Money
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set price
     *
     * @param Money $price
     * @return TestMoney
     */
    public function setPrice(Money $price)
    {
        $this->price = $price;
        return $this;
    }
}

转换管理器

将金额转换为另一种货币

$pairManager = $this->get("phil_money.pair_manager");
$usd = $pairManager->convert($amount, 'USD');

将转换值保存到数据库中

use Money\Money;

$pairManager = $this->get("phil_money.pair_manager");
$pairManager->saveRatio('USD', 1.25); // save in ratio file in CSV
$eur = Money::EUR(100);
$usd = $pairManager->convert($amount, 'USD');
$this->assertEquals(Money::USD(125), $usd);

货币格式化

<?php

namespace My\Controller\IndexController;

use Money\Money;
use Money\Currency;

class IndexController extends Controller
{
    public function myAction()
    {
        $moneyFormatter = $this->get('phil_money.formatter.money_formatter');
        $price = new Money(123456789, new Currency('EUR'));

        \Locale::setDefault('fr_FR');
        $formatedPrice = $moneyFormatter->localizedFormatMoney($price);
        // 1 234 567,89 €
        $formatedPrice = $moneyFormatter->localizedFormatMoney($price, 'en');
        // €1,234,567.89
    }
}

Twig集成

{{ $amount | money_localized_format('fr') }} => 1 234 567,89 €
{{ $amount | money_localized_format('en_US') }} => €1,234,567.89
{{ $amount | money_localized_format }} => depends on your default locale
{{ $amount | money_format }}
{{ $amount | money_as_float }}
{{ $amount | money_get_currency | currency_symbol }}
{{ $amount | money_get_currency | currency_name }}
{{ $amount | money_convert("USD") | money_format }}
{{ $amount | money_format_currency }}

PHP模板集成

<span class="price"><?php echo $view['phil_money']->format($price) ?></span>
<span class="money"><?php echo $view['phil_money_currency']->formatCurrencyAsSymbol($price->getCurrency()) ?></span>

从远程提供者获取比率值

# save a ratio in the storage
./bin/console phil:money:ratio-save USD 1.25

# display ratio list
./bin/console phil:money:ratio-list

# fetch all the ratio for all defined currencies from an external API
./bin/console phil:money:ratio-fetch

更改比率提供者

默认的比率提供者是基于服务 'phil_money.ratio_provider.ecb'

此包包含一个比率提供者

您可以在 config.yml 文件中更改要使用的服务

phil_money:
    [...]
    ratio_provider: phil_money.ratio_provider.ecb

来自 Exchanger 的额外汇率提供者

此项目集成了 https://github.com/florianv/exchanger 库,以处理来自各种服务的货币汇率。

安装

composer require "florianv/exchanger" "php-http/message" "php-http/guzzle6-adapter"

配置

首先,您需要将您想使用的服务添加到您的 services.yml 文件中,例如

ratio_provider.service.ecb:
  class: Exchanger\Service\EuropeanCentralBank

其次,您需要更新 MoneyBundle 使用的比率提供者在您的 config.yml 文件上

phil_money:
    [...]
    ratio_provider: ratio_provider.service.ecb

推荐

一些提供者专注于有限的货币组合,但提供更好的数据。您可以通过将它们捆绑到链中,无缝地在项目中使用多个汇率提供者。如果某些提供者不支持某种货币,则链中的下一个提供者将被尝试。

链式提供者的示例

ratio_provider.service.ecb:
  class: Exchanger\Service\EuropeanCentralBank

ratio_provider.service.rcb:
  class: Exchanger\Service\RussianCentralBank

ratio_provider.service.cryptonator:
  class: Exchanger\Service\Cryptonator

ratio_provider.service.array:
  class: Exchanger\Service\PhpArray
  arguments:
    -
      'EUR/USD': 1.157
      'EUR/AUD': 1.628

ratio_provider.service.default:
  class: Exchanger\Service\Chain
  arguments:
    -
      - "@ratio_provider.service.ecb"
      - "@ratio_provider.service.rcb"
      - "@ratio_provider.service.cryptonator"
      - "@ratio_provider.service.array"

如您所见,将尝试 4 个提供者,直到找到转换率。查看此页以获取支持的完整服务列表及其配置:https://github.com/florianv/exchanger/blob/master/doc/readme.md#supported-services

然后您需要在您的 config.yml 文件上分配汇率提供者

phil_money:
    [...]
    ratio_provider: ratio_provider.service.default

创建您自己的比率提供者

比率提供者是一个实现 Phil\MoneyBundle\Pair\RatioProviderInterface 的服务。我建议您阅读该接口的 PHP 文档,以了解如何实现新的比率提供者。

新的比率提供者必须注册为服务。

要使用新的比率提供者,您应该通过给出服务名称来设置在 config.yml 中使用的服务。

phil_money:
    [...]
    ratio_provider: phil_money.ratio_provider.google

自动货币比率抓取

添加到您的 crontab 中

1 0 * * * /my_app_dir/bin/console phil:money:ratio-fetch > /dev/null

MoneyManager:从浮点数创建货币对象

从浮点数创建货币对象可能有些棘手,因为存在舍入问题。

<?php
$moneyManager = $this->get("phil_money.money_manager");
$money = $moneyManager->createMoneyFromFloat('2.5', 'USD');
$this->assertEquals("USD", $money->getCurrency()->getCode());
$this->assertEquals(250, $money->getAmount());

使用 pairHistoryManager 的货币比率历史

使用此功能需要 Doctrine。

为了获取比率历史,您必须在配置中启用它并使用 Doctrine。

phil_money:
    currencies: ["USD", "EUR"]
    reference_currency: "EUR"
    enable_pair_history: true

然后您可以使用此服务

$pairHistoryManager = $this->get("phil_money.pair_history_manager");
$dt = new \DateTime("2012-07-08 11:14:15.638276");

// returns ratio for at a given date
$ratio = $pairHistoryManager->getRatioAtDate('USD',$dt);

// returns the list of USD ratio (relative to the reference value)
$ratioList = $pairHistoryManager->getRatioHistory('USD',$startDate, $endDate);

存储

可用于存储比率的两个存储选项:CSV 文件或 Doctrine。默认情况下,PhilMoneyBundle 配置为使用 CSV 文件。

如果您想切换到 Doctrine 存储,请编辑您的 config.yml

phil_money:
    storage: doctrine

更新您的数据库模式

./bin/console doctrine:schema:update --force

使用 Doctrine 存储,货币比率将使用默认的实体管理器,并将数据存储在 phil_money_doctrine_storage_ratios

MoneyFormatter 中的自定义 NumberFormatter

MoneyFormatter::localizedFormatMoney(服务 'phil_money.formatter.money_formatter')使用 php NumberFormatter 类(https://php.ac.cn/manual/en/numberformatter.formatcurrency.php)来格式化货币。

您可以使用以下方式

  • 将您的自己的 \NumberFormatter 实例作为 MoneyFormatter::localizedFormatMoney 的参数
  • 子类化 MoneyFormatter 并重写 getDefaultNumberFormater 方法以设置应用程序范围的 NumberFormatter

在不使用 Doctrine 的情况下使用 PhilMoneyBundle

为了在不使用 Doctrine 的情况下使用 PhilMoneyBundle,您必须禁用对历史记录服务的使用。

phil_money:
    enable_pair_history: true

注意:您可以想象自己为MongoDB或Propel编写自己的PairHistoryManager,这非常简单。不要犹豫,提交包含您代码和测试的PR。

优化

在您的config.yml中,您可以

  • 选择要使用的模板引擎。默认情况下,仅加载Twig。
  • 定义单位后的小数位数(例如:12.25€:2位小数;11.5678€:4位小数)
phil_money:
    currencies: ["USD", "EUR"]
    reference_currency: "EUR"
    decimals: 2
    enable_pair_history: true
    ratio_provider: phil_money.ratio_provider.yahoo_finance

贡献

  1. 查看问题列表
  2. Fork
  3. 编写测试(无论是新功能还是错误)
  4. 创建PR

要求

  • PHP 8.1.2+
  • Symfony 6.3+

作者

Philippe Gamache: [ph-il.ca][https://ph-il.ca] Philippe Le Van - kitpages.fr - x: @plv
Thomas Tourlourat - x: @armetiz

状态

稳定

什么是有功能的

  • 货币库集成
  • 配置解析器
  • 配对管理器
  • Travis CI集成
  • 表单集成
  • 表单的Twig展示
  • Twig过滤器
  • 创建和显示比例的命令
  • 自动获取比例(使用2个比例提供者)
  • 货币比例历史记录