Installation Add the bundle via Composer:
composer require dotdev/currency-bundle
Enable it in config/bundles.php:
return [
// ...
Dotdev\CurrencyBundle\DotdevCurrencyBundle::class => ['all' => true],
];
Configuration
Define currencies in config/packages/dotdev_currency.yaml:
dotdev_currency:
base_currency: 'USD'
currencies:
USD: {name: 'US Dollar', symbol: '$'}
EUR: {name: 'Euro', symbol: '€'}
First Use Case Fetch a currency in a controller/service:
use Dotdev\CurrencyBundle\Currency\CurrencyRepositoryInterface;
public function showCurrency(CurrencyRepositoryInterface $currencyRepository)
{
$usd = $currencyRepository->find('USD');
return new Response($usd->getSymbol());
}
Currency Conversion
Use the CurrencyConverter service to convert amounts:
$converter = $this->container->get('dotdev_currency.converter');
$amountInEur = $converter->convert(100, 'USD', 'EUR'); // Returns ~85.53
Dynamic Currency Handling
Attach currencies to entities (e.g., Order, Product) via traits:
use Dotdev\CurrencyBundle\Currency\CurrencyAwareTrait;
class Order implements CurrencyAwareInterface
{
use CurrencyAwareTrait;
// ...
}
API Integration Serialize currencies in API responses:
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
$normalizer = new ObjectNormalizer();
$normalizer->setIgnoredAttributes(['currencyCode']);
$serialized = $normalizer->normalize($order);
CurrencyType for database fields:
use Dotdev\CurrencyBundle\Doctrine\DBAL\Types\CurrencyType;
$builder->addColumn('price', CurrencyType::CURRENCY);
$builder->add('currency', CurrencyType::class, [
'choices' => $currencyRepository->getAll(),
]);
$eventDispatcher->addListener(
CurrencyEvents::RATE_UPDATED,
[$this, 'onRateUpdated']
);
Base Currency Dependency
base_currency setting. Ensure it’s correctly configured in dotdev_currency.yaml.dump($converter->getBaseCurrency()) to verify.Caching Exchange Rates
$converter->setCache($cachePool); // Inject Symfony Cache component
Entity Lifecycle
CurrencyAwareTrait, ensure setCurrency() is called before saving entities to avoid null values.Archived Status
CurrencyNotFoundException. Validate codes against CurrencyRepository::getAll().CurrencyEvents::RATE_UPDATED to track dynamic changes:
$logger->info('Rate updated', ['from' => $event->getFrom(), 'to' => $event->getTo()]);
Custom Rate Providers Override the default provider (e.g., for internal APIs):
dotdev_currency:
rate_provider: app.custom_rate_provider
// src/Service/CustomRateProvider.php
class CustomRateProvider implements RateProviderInterface { ... }
Validation Add constraints to currency fields:
use Dotdev\CurrencyBundle\Validator\Constraints\ValidCurrency;
$builder->add('currency', CurrencyType::class, [
'constraints' => [new ValidCurrency()]
]);
Testing
Mock the CurrencyRepository in tests:
$currencyRepo = $this->createMock(CurrencyRepositoryInterface::class);
$currencyRepo->method('find')->willReturn(new Currency('USD'));
$this->container->set('dotdev_currency.repository', $currencyRepo);
```markdown
### Pro Tips
- **Multi-Currency UI**: Use Twig filters for dynamic symbols:
```twig
{{ order.total|dotdev_currency_symbol(order.currency) }} {{ order.total|dotdev_currency_format(order.currency) }}
dotdev_currency:
default_rates:
USD: {EUR: 0.8553, GBP: 0.7344}
CurrencyNormalizer.How can I help you explore Laravel packages today?