msonowal/ laraxchange
该包通过使用http://fixer.io/ API提供Laravel应用的多货币转换功能,并使用指定的缓存驱动程序缓存汇率,通过Laravel的命令总线定期更新应用缓存
v1.2.3
2019-05-04 07:26 UTC
Requires
- php: >=7.0
- guzzlehttp/guzzle: ~6.2
- illuminate/cache: 5.5.*|5.6.*|5.7.*
- illuminate/session: 5.5.*|5.6.*|5.7.*
- illuminate/support: 5.5.*|5.6.*|5.7.*
Suggests
- geoip2/geoip2: Required to use the MaxMind database or web service with GeoIP (~2.1).
- torann/geoip: Required to use the middleware for determining default currency by the request location and setting it in the session (^1.0).
README
Laravel 5多货币转换库,当前使用http://fixer.io/ API。
支持所有Laravel 5.*版本。
与其他需要配置提供者的包不同,此库调用免费服务,无需任何配置即可使用。该包使用内置的Laravel缓存驱动来缓存汇率,并提供Artisan命令,可以安排定期更新缓存存储。
因此,您无需担心下载/配置API密钥。
它还提供了一个中间件,可以自动确定货币并设置访客的货币,如果没有在会话中设置货币,则依赖于GeoIp 包
只需安装包,添加配置即可使用!
要求
- PHP >= 5.6.*
- 从此处安装Geoip包
安装
composer require msonowal/laraxchange
在config/app.php中添加服务提供者和外观
服务提供者
Msonowal\Laraxchange\Providers\CurrencyServiceProvider::class,
别名(外观)
'Currency' => Msonowal\Laraxchange\Facades\Currency::class,
配置
此库还支持可选配置。
要开始使用,首先发布包配置文件
php artisan vendor:publish --provider="Msonowal\Laraxchange\Providers\CurrencyServiceProvider"
base_currency
:定义应用的基础货币。default_currency
:定义没有转换货币代码时的默认货币。valid_currencies
:定义允许应用于应用的货币。cache_key
:定义存储和检索时使用的缓存键。cache_expiry
:定义缓存有效期,单位为分钟,货币将在缓存中存储多长时间。
它提供各种内置辅助方法来获取用户货币或设置货币。
使用方法
使用中间件设置访客的默认货币,在app/http的Kernal.php中添加以下内容
'determine_currency' => \Msonowal\Laraxchange\Middleware\SetDefaultUserCurrency::class,
获取访客的ISO货币代码
getUserCurrency(); // returns "USD"
获取访客的ISO货币代码
getUserCurrencySymbol(); // returns "$"
获取货币的ISO货币符号
getCurrencySymbol("USD"); // returns "$"
实时将值从基础货币转换为另一种货币
convertCurrency($value, "GBP"); // returns the value in GBP currency
仅设置基础货币,实例可以实时更改
Currency::setBaseCurrency("GBP"); // sets the base currency as specified for that instance when default base currency is different
获取基于指定基础货币的所有货币转换列表
Currency::getRates(); // returns list of values fore each currency
使用命令缓存汇率
php artisan currency:cache; // will cache currency conversion rates for each available currency specified in config `valid_currencies`
要自动缓存汇率,请将以下命令添加到app/Console目录下的Kernal.php中
$schedule->command('currency:cache')->daily()->at('12:00'); // will cache currency conversion rates for each available currency specified in config `valid_currencies`
还有许多其他方法可以由您自己探索