rikless/laravel-currency

Laravel 5+ 的货币组件

v1.4.5 2022-01-04 09:02 UTC

README

Build Status

版本

从版本 v1.3.0 开始,该软件包需要 PHP 7.1。对于 PHP 的早期版本,请使用 v1.2.0

安装

使用 composer 安装软件包

composer require sebastiansulinski/laravel-currency

服务提供者和外观

要使用 IOC 容器中的包,请将 SSD\Currency\CurrencyServiceProvider 添加到 config/app.php 中的 providers 列表

'providers' => [
    ...

    SSD\Currency\CurrencyServiceProvider::class

]

要使用外观,请将其添加到 aliases

'aliases' => [
    ...

    'Currency'  => SSD\Currency\CurrencyFacade::class
]

现在运行

php artisan vendor:publish

这将添加一个新文件 config/currency.php,具有以下结构

<?php

return [
    "key" => "currency",
    "default" => "gbp",
    "currencies" => [
        "gbp" => \SSD\Currency\Currencies\GBP::class,
        "usd" => \SSD\Currency\Currencies\USD::class,
        "eur" => \SSD\Currency\Currencies\EUR::class
    ],
    "value_as_integer" => false
];
  • key 用于作为会话密钥,用于存储当前所选货币。
  • default 表示默认货币。
  • currencies 包含可用货币列表。
  • value_as_integer 指示您的价格是否以整数或浮点/十进制存储。

提供者

软件包包含两个实现/提供者

  • SSD\Currency\Providers\CookieProvider,它将所选货币存储在加密的 cookie 中
  • SSD\Currency\Providers\SessionProvider,它将使用默认会话驱动程序存储所选货币

您可以通过

  • 扩展 SSD\Currency\Providers\BaseProvider 来创建额外的提供者

新提供者需要实现 3 个方法 - 这些是: getsetis。请参阅 SSD\Currency\Providers\CookieProvider 以获得更好的了解。

一旦准备好新实现,请创建新的 ServiceProvider 并将其替换到 config/app.php 中。

添加更多货币

软件包包含 3 种货币: GBPUSDEUR

如果您想添加更多,首先创建一个新的货币类,该类

  • 扩展 SSD\Currency\Currencies\BaseCurrency

例如,日本货币的实现(假设您将货币放在 App\Components\Currencies 命名空间下)

<?php 

namespace App\Components\Currencies;

use SSD\Currency\Currencies\BaseCurrency;

class JPY extends BaseCurrency
{
    /**
     * @var string
     */
    protected $prefix = '¥';

    /**
     * @var string
     */
    protected $postfix = 'JPY';
}

现在,您只需将其添加到 config/currency.php 文件中即可使用它

<?php

return [
    "key" => "currency",
    "default" => "gbp",
    "currencies" => [
        "gbp" => \SSD\Currency\Currencies\GBP::class,
        "usd" => \SSD\Currency\Currencies\USD::class,
        "eur" => \SSD\Currency\Currencies\EUR::class,
        "jpy" => \App\Components\Currencies\JPY::class
    ],
    "value_as_integer" => false
];

使用示例

显示货币最常见的方式是将它们显示为可点击按钮或作为表单 select 菜单,以下将演示这一点。

首先,让我们创建一个包含所有选项的表单选择元素。我们可以使用 Currency 外观或简单地使用 app('currency') 从容器中获取 currency

<form>
    <select id="currency">
        @foreach(app('currency')->options() as $option)
            <option 
                value="/currency/{{ $option->value }}"
                {{ app('currency')->selected($option->value) }}
            >{{ $option->label }}</option>
        @endforeach
    </select>
</form>

现在我们需要一些 JavaScript,以便在 change 事件发生时,调用给定的路由,其中控制器操作设置新货币并刷新页面以反映更改。

只需使用 JavaScript 将 change 事件绑定到 select 元素即可

// vanilla JavaScript
(document.getElementById('currency')).addEventListener('change', function(event) {
    window.location.href = event.target.value;
});

// or using jQuery
$('#currency').on('change', function() {
    window.location.href = $(this).val();
});

接下来,我们需要添加具有操作和路由的控制器

// app/Http/routes.php

Route::get('currency/{currency_id}', 'CurrencyController@set');
// app/Http/Controllers/CurrencyController.php

<?php 

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;

use Currency;

class CurrencyController extends Controller
{
    /**
     * Set currency cookie.
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function set($id)
    {
        Currency::set($id);

        return new JsonResponse(['success' => true]);
    }
}

如果您想根据所选货币显示价格,请确保您的模型可以为给定项目提供以下格式的价格数组

[
    'gbp' => 10.00,
    'eur' => 11.56,
    'usd' => 17.60,
    'jpy' => 18.50
]

// or if you're using prices as integers

[
    'gbp' => 1000,
    'eur' => 1156,
    'usd' => 1760,
    'jpy' => 1850
]

假设我们的 Product 模型有一个 prices() 方法,它将返回上述格式的数组。要使用它,您现在可以简单地调用

/**
 * Array of prices.
 *
 * @return array
 */
public function prices()
{
    return [
        'gbp' => $this->price_gbp,
        'usd' => $this->price_usd,
        'eur' => $this->price_eur,
        'jpy' => $this->price_jpy
    ];
}

/**
 * Price formatted with the currency symbol.
 *
 * @return string
 */
public function priceDisplay()
{
    return Currency::withPrefix($this->prices(), null, 2);
}

priceDisplay() 方法将返回带货币符号的价格,例如 £10.00(取决于当前所选货币)。

格式化方法

我们的 Currency 对象上有以下方法可用

  • decimal($values, $currency = null, $decimal_points = 2) : 获取值并以小数格式返回。
  • integer($values, $currency = null) : 获取整数形式的值,即 20.53 将变为 20,但 2053 将保持 2053
  • withPrefix($values, $currency = null, $decimal_points = null) : 获取值并在其前加上货币符号。
  • withPostfix($values, $currency = null, $decimal_points = null) : 获取值并在其后加上货币代码。
  • withPrefixAndPostfix($values, $currency = null, $decimal_points = null) : 获取值并在其前后都加上货币符号和代码。

以上四个方法中,有四个方法接受三个参数(只有 integer 方法只接受前两个)。

  • $values : 如上所述的数组或单个浮点数 / 整数。
  • $currency : 默认为 null,此时将从 cookie 中获取货币,否则可以指定要使用的货币。
  • $decimal_points : 要返回值的小数点数。

更多方法

  • options() : 返回一个包含 SSD\Currency\Option 的数组 - 每个对象代表一种货币。 SSD\Currency\Option 有两个属性 valuelabel
  • selected($currency) : 与 select option 元素一起使用,如果设置当前选项,则将其设置为 selected="selected"
  • get() : 获取当前选定的货币。
  • set($currency) : 设置货币。
  • is($currency) : 检查传递给参数的货币是否当前选中。