PHPackages                             tourze/currency-manage-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. tourze/currency-manage-bundle

ActiveSymfony-bundle[Utility &amp; Helpers](/categories/utility)

tourze/currency-manage-bundle
=============================

A Symfony bundle for currency management with exchange rate synchronization

1.0.1(6mo ago)09862MITPHPCI passing

Since May 9Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/tourze/currency-manage-bundle)[ Packagist](https://packagist.org/packages/tourze/currency-manage-bundle)[ RSS](/packages/tourze-currency-manage-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (45)Versions (5)Used By (2)

Currency Management Bundle
==========================

[](#currency-management-bundle)

[![PHP Version](https://camo.githubusercontent.com/10d1e1006c525ba84664ffdd58536d0217519a8e10be1ae4b355d7b671aa8913/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f746f75727a652f63757272656e63792d6d616e6167652d62756e646c65)](https://packagist.org/packages/tourze/currency-manage-bundle)[![License](https://camo.githubusercontent.com/776de92ff4dea45ccaadc784471f4cff19c845da4fc9f5fbd31bbae0abb246e3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f75727a652f63757272656e63792d6d616e6167652d62756e646c65)](https://packagist.org/packages/tourze/currency-manage-bundle)

[![CI Status](https://camo.githubusercontent.com/33d8d6a84f331d0bed85045f7d4dc58808640478bab748a54f73dd3db4503ad2/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f746f75727a652f63757272656e63792d6d616e6167652d62756e646c652f63692e796d6c3f6272616e63683d6d61696e)](https://github.com/tourze/currency-manage-bundle/actions)[![Code Coverage](https://camo.githubusercontent.com/568ad6ec7bb0e24fe873e70e61b75d1e171a4be90f2df7b9990dafe523be18de/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f746f75727a652f63757272656e63792d6d616e6167652d62756e646c65)](https://codecov.io/gh/tourze/currency-manage-bundle)

[English](README.md) | [中文](README.zh-CN.md)

A Currency Management Bundle for Symfony that provides currency information management and exchange rate updates.

目录
--

[](#目录)

- [功能特性](#%E5%8A%9F%E8%83%BD%E7%89%B9%E6%80%A7)
- [安装](#%E5%AE%89%E8%A3%85)
- [配置](#%E9%85%8D%E7%BD%AE)
    - [1. 注册 Bundle](#1-%E6%B3%A8%E5%86%8C-bundle)
    - [2. 数据库迁移](#2-%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%81%E7%A7%BB)
    - [3. 路由配置](#3-%E8%B7%AF%E7%94%B1%E9%85%8D%E7%BD%AE)
- [使用方法](#%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95)
    - [货币实体](#%E8%B4%A7%E5%B8%81%E5%AE%9E%E4%BD%93)
    - [历史汇率实体](#%E5%8E%86%E5%8F%B2%E6%B1%87%E7%8E%87%E5%AE%9E%E4%BD%93)
    - [历史汇率查询](#%E5%8E%86%E5%8F%B2%E6%B1%87%E7%8E%87%E6%9F%A5%E8%AF%A2)
    - [国旗服务](#%E5%9B%BD%E6%97%97%E6%9C%8D%E5%8A%A1)
    - [汇率更新命令](#%E6%B1%87%E7%8E%87%E6%9B%B4%E6%96%B0%E5%91%BD%E4%BB%A4)
- [国旗映射](#%E5%9B%BD%E6%97%97%E6%98%A0%E5%B0%84)
- [国旗图片接口](#%E5%9B%BD%E6%97%97%E5%9B%BE%E7%89%87%E6%8E%A5%E5%8F%A3)
- [EasyAdmin 管理界面](#easyadmin-%E7%AE%A1%E7%90%86%E7%95%8C%E9%9D%A2)
- [Advanced Usage](#advanced-usage)
- [测试](#%E6%B5%8B%E8%AF%95)
- [数据库表结构](#%E6%95%B0%E6%8D%AE%E5%BA%93%E8%A1%A8%E7%BB%93%E6%9E%84)
- [性能优化](#%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96)
- [数据清理](#%E6%95%B0%E6%8D%AE%E6%B8%85%E7%90%86)
- [依赖](#%E4%BE%9D%E8%B5%96)
- [许可证](#%E8%AE%B8%E5%8F%AF%E8%AF%81)

功能特性
----

[](#功能特性)

- 货币实体管理（名称、代码、符号、汇率等）
- 自动汇率更新（通过定时任务）
- **历史汇率记录和查询**
- 国旗图标支持（基于 lipis/flag-icons）
- EasyAdmin 后台管理界面
- 完整的单元测试覆盖

安装
--

[](#安装)

```
composer require tourze/currency-manage-bundle
```

配置
--

[](#配置)

### 1. 注册 Bundle

[](#1-注册-bundle)

在 `config/bundles.php` 中添加：

```
return [
    // ...
    Tourze\CurrencyManageBundle\CurrencyManageBundle::class => ['all' => true],
];
```

### 2. 数据库迁移

[](#2-数据库迁移)

```
php bin/console doctrine:migrations:diff
php bin/console doctrine:migrations:migrate
```

### 3. 路由配置

[](#3-路由配置)

Bundle 使用 `AttributeControllerLoader` 自动注册路由，包括：

- `/currency/flag/{code}` - 获取 4x3 比例的国旗图片
- `/currency/flag/{code}/1x1` - 获取 1x1 比例的国旗图片

使用方法
----

[](#使用方法)

### 货币实体

[](#货币实体)

```
use Tourze\CurrencyManageBundle\Entity\Currency;

$currency = new Currency();
$currency->setName('美元');
$currency->setCode('USD');
$currency->setSymbol('$');
$currency->setRateToCny(7.2);
```

### 历史汇率实体

[](#历史汇率实体)

```
use Tourze\CurrencyManageBundle\Entity\CurrencyRateHistory;

$history = new CurrencyRateHistory();
$history->setCurrencyCode('USD');
$history->setCurrencyName('美元');
$history->setCurrencySymbol('$');
$history->setFlag('us');
$history->setRateToCny(7.2);
$history->setRateDate(new \DateTime('2025-01-01'));
```

### 历史汇率查询

[](#历史汇率查询)

```
use Tourze\CurrencyManageBundle\Repository\CurrencyRateHistoryRepository;

// 根据货币代码查询历史汇率
$histories = $repository->findByCurrencyCode('USD', 30);

// 根据日期范围查询
$startDate = new \DateTime('2025-01-01');
$endDate = new \DateTime('2025-01-31');
$histories = $repository->findByDateRange($startDate, $endDate, 'USD');

// 获取最新历史汇率
$latest = $repository->findLatestByCurrency('USD');

// 获取统计信息
$stats = $repository->getStatistics();
```

### 国旗服务

[](#国旗服务)

```
use Tourze\CurrencyManageBundle\Service\FlagService;

$flagService = new FlagService();

// 获取国旗文件路径
$flagPath = $flagService->getFlagPath('us', '4x3');

// 检查国旗是否存在
$exists = $flagService->flagExists('us');

// 根据货币代码获取国旗代码
$flagCode = $flagService->getFlagCodeFromCurrency('USD'); // 返回 'us'

// 获取所有可用的国旗代码
$availableFlags = $flagService->getAvailableFlags();
```

### 汇率更新命令

[](#汇率更新命令)

```
# 手动更新汇率（同时记录历史数据）
php bin/console currency-manage:update-rate

# 定时任务会在每天 8:40 自动执行
```

国旗映射
----

[](#国旗映射)

Bundle 支持 176+ 种货币的国旗映射，覆盖率达到 61.75%，包括：

### 主要货币

[](#主要货币)

- CNY → cn (中国)
- USD → us (美国)
- EUR → eu (欧盟)
- JPY → jp (日本)
- GBP → gb (英国)
- 等等...

### 特殊处理

[](#特殊处理)

- 历史货币映射到对应的国家/地区
- 货币联盟使用代表性国家的国旗
- 贵金属等特殊货币返回 null

国旗图片接口
------

[](#国旗图片接口)

### 获取国旗图片

[](#获取国旗图片)

```
GET /currency/flag/{code}

```

参数：

- `code`: 国旗代码（如：us, cn, eu）

返回：SVG 格式的国旗图片

示例：

```
GET /currency/flag/us
GET /currency/flag/cn/1x1

```

EasyAdmin 管理界面
--------------

[](#easyadmin-管理界面)

Bundle 提供了完整的 EasyAdmin 管理界面：

1. **货币管理** - 管理货币基本信息和当前汇率
2. **历史汇率** - 查看和管理历史汇率记录（只读）

管理界面支持：

- 搜索和过滤
- 分页显示
- 详情查看
- 数据导出

Advanced Usage
--------------

[](#advanced-usage)

### 自定义汇率更新服务

[](#自定义汇率更新服务)

```
use Tourze\CurrencyManageBundle\Service\CurrencyRateService;

class CustomCurrencyService
{
    public function __construct(
        private CurrencyRateService $currencyRateService
    ) {}

    public function updateRatesFromCustomSource(): array
    {
        // 自定义汇率更新逻辑
        $exchangeData = $this->fetchFromCustomAPI();

        $results = [];
        foreach ($exchangeData as $code => $rate) {
            $result = $this->currencyRateService->updateCurrencyRate(
                $code,
                $this->getCurrencyName($code),
                $rate,
                new \DateTimeImmutable(),
                new \DateTimeImmutable()
            );
            $results[] = $result;
        }

        return $results;
    }
}
```

### 扩展国旗映射

[](#扩展国旗映射)

```
use Tourze\CurrencyManageBundle\Service\FlagService;

class ExtendedFlagService extends FlagService
{
    protected function getCustomMappings(): array
    {
        return [
            'BTC' => 'bitcoin',  // 自定义映射
            'ETH' => 'ethereum',
            // 添加更多自定义映射...
        ];
    }
}
```

### 历史汇率分析

[](#历史汇率分析)

```
use Tourze\CurrencyManageBundle\Repository\CurrencyRateHistoryRepository;

class CurrencyAnalyzer
{
    public function __construct(
        private CurrencyRateHistoryRepository $historyRepository
    ) {}

    public function calculateVolatility(string $currencyCode, int $days = 30): float
    {
        $histories = $this->historyRepository->findByCurrencyCode($currencyCode, $days);

        if (count($histories) < 2) {
            return 0.0;
        }

        $rates = array_map(fn($h) => $h->getRateToCny(), $histories);
        $mean = array_sum($rates) / count($rates);

        $variance = array_sum(array_map(fn($r) => pow($r - $mean, 2), $rates)) / count($rates);

        return sqrt($variance);
    }
}
```

### 事件监听

[](#事件监听)

```
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Tourze\CurrencyManageBundle\Event\CurrencyRateUpdatedEvent;

class CurrencyEventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            CurrencyRateUpdatedEvent::class => 'onCurrencyRateUpdated',
        ];
    }

    public function onCurrencyRateUpdated(CurrencyRateUpdatedEvent $event): void
    {
        // 汇率更新后的自定义处理逻辑
        $currency = $event->getCurrency();
        $oldRate = $event->getOldRate();
        $newRate = $event->getNewRate();

        // 例如：发送通知、更新缓存等
    }
}
```

测试
--

[](#测试)

```
# 运行所有测试
./vendor/bin/phpunit packages/currency-manage-bundle/tests

# 运行特定测试
./vendor/bin/phpunit packages/currency-manage-bundle/tests/Service/FlagServiceTest.php

# 查看货币映射覆盖率
./vendor/bin/phpunit packages/currency-manage-bundle/tests/Service/CurrencyMappingCoverageTest.php

# 测试历史汇率功能
./vendor/bin/phpunit packages/currency-manage-bundle/tests/Entity/CurrencyRateHistoryTest.php
./vendor/bin/phpunit packages/currency-manage-bundle/tests/Repository/CurrencyRateHistoryRepositoryTest.php
```

数据库表结构
------

[](#数据库表结构)

### 货币表 (starhome\_currency)

[](#货币表-starhome_currency)

- `id` - 主键
- `name` - 货币名称
- `code` - 货币代码
- `flags` - 货币符号
- `flag` - 国旗代码
- `rateToCny` - 对人民币汇率
- `rateUpdateDate` - 汇率更新时间

### 历史汇率表 (starhome\_currency\_rate\_history)

[](#历史汇率表-starhome_currency_rate_history)

- `id` - 主键
- `currency_code` - 货币代码
- `currency_name` - 货币名称
- `currency_symbol` - 货币符号
- `flag` - 国旗代码
- `rateToCny` - 对人民币汇率
- `rate_date` - 汇率日期
- `createdAt` - 记录创建时间

索引：

- `idx_currency_code` - 货币代码索引
- `idx_rate_date` - 汇率日期索引
- `idx_currency_date` - 货币代码+日期复合索引

性能优化
----

[](#性能优化)

1. **数据库索引** - 为常用查询字段添加索引
2. **缓存策略** - 国旗图片设置缓存头
3. **批量操作** - 汇率更新使用批量提交

数据清理
----

[](#数据清理)

为避免历史数据无限增长，可以定期清理旧数据：

```
// 删除一年前的历史记录
$cutoffDate = new \DateTime('-1 year');
$deletedCount = $repository->deleteBeforeDate($cutoffDate);
```

依赖
--

[](#依赖)

- PHP 8.1+
- Symfony 6.4+
- Doctrine ORM 3.0+
- lipis/flag-icons 7.3+

许可证
---

[](#许可证)

MIT

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance72

Regular maintenance activity

Popularity14

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~62 days

Total

4

Last Release

182d ago

Major Versions

0.0.2 → 1.0.02025-11-05

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (7 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-currency-manage-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-currency-manage-bundle/health.svg)](https://phpackages.com/packages/tourze-currency-manage-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
