Installation:
composer require cocolabs-sas/currency-bundle
Ensure the bundle is registered in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 2/3):
Lexik\Bundle\CurrencyBundle\LexikCurrencyBundle::class => ['all' => true],
Basic Configuration (config/packages/lexik_currency.yaml):
lexik_currency:
currencies:
default: USD
managed:
- EUR
- GBP
- JPY
First Use Case: Use the Twig filter in a template to format a value:
{{ 1234.56 | currency_format('EUR') }} {# Outputs: €1,234.56 #}
Or convert and format:
{{ 1234.56 | currency_convert_format('EUR', 'GBP') }} {# Converts USD to GBP #}
Currency Conversion in Controllers:
Inject the currency_converter service to programmatically convert currencies:
use Lexik\Bundle\CurrencyBundle\Services\CurrencyConverter;
public function __construct(CurrencyConverter $converter) {
$this->converter = $converter;
}
public function convertCurrency(Request $request) {
$amount = $request->request->get('amount');
$converted = $this->converter->convert($amount, 'USD', 'EUR');
return new Response($converted);
}
Dynamic Currency Selection: Use a user’s locale or session to dynamically set the currency:
{% set userCurrency = app.user.preferred_currency ?: 'USD' %}
{{ order.total | currency_format(userCurrency) }}
Database Storage: Store amounts in a base currency (e.g., USD) in the database and convert on display:
// Store in DB (always in USD)
$product->price = 99.99;
// Display in user's currency
{{ product.price | currency_convert_format('USD', app.user.currency) }}
API Responses: Return formatted currencies in JSON responses:
return $this->json([
'price' => $product->price,
'formatted_price' => $product->price | currency_convert_format('USD', 'EUR')
]);
Localization:
Ensure your app’s locales are configured in config/packages/lexik_currency.yaml:
lexik_currency:
locales:
EUR: 'fr_FR'
GBP: 'en_GB'
Symfony Forms:
Use the CurrencyType for form fields:
$builder->add('price', CurrencyType::class, [
'currency' => 'EUR',
'scale' => 2,
]);
Caching Conversions: Cache conversion rates to avoid repeated API calls (e.g., using Symfony’s cache system):
lexik_currency:
cache: cache.app
Custom Number Formatters: Extend the bundle’s formatter for bespoke rules:
// src/Service/CustomCurrencyFormatter.php
use Lexik\Bundle\CurrencyBundle\Formatter\CurrencyFormatter;
class CustomCurrencyFormatter extends CurrencyFormatter {
public function format($amount, $currency, $locale = null) {
// Custom logic (e.g., rounding, symbols)
return parent::format($amount, $currency, $locale);
}
}
Register as a service:
services:
lexik_currency.formatter:
class: App\Service\CustomCurrencyFormatter
tags: ['lexik_currency.formatter']
Deprecated Filters:
currency_format for conversions (use currency_convert_format instead).{{ 100 | currency_format('USD', 'EUR') }} {# Fails: Wrong signature #}
Locale Mismatches:
locale config matches the currency’s region (e.g., en_US for USD, fr_FR for EUR).$1,000 vs. 1.000,00).Unmanaged Currencies:
managed can be converted. Attempting to convert an unmanaged currency (e.g., currency_convert_format('USD', 'XYZ')) throws an exception.Floating-Point Precision:
round() or number_format() in Twig:
{{ (100 | currency_convert_format('USD', 'EUR') | round(2)) | currency_format('EUR') }}
Check Conversion Rates: Dump the converter’s rates to verify data:
$rates = $this->converter->getRates();
dump($rates); {# Should show exchange rates like ['EUR' => 0.85, 'GBP' => 0.75] #}
Twig Debugging: Enable Twig strict mode to catch filter errors:
twig:
strict_variables: true
Service Overrides: If extending the bundle, clear the cache after updates:
php bin/console cache:clear
Custom Exchange Rate Provider: Replace the default rate provider (e.g., for internal APIs):
lexik_currency:
provider: app.custom_rate_provider
Implement Lexik\Bundle\CurrencyBundle\Provider\RateProviderInterface.
Event Listeners: Listen for currency conversion events to log or audit changes:
use Lexik\Bundle\CurrencyBundle\Event\CurrencyConvertEvent;
public function onCurrencyConvert(CurrencyConvertEvent $event) {
// Log conversion details
}
Register as a service with the kernel.event_listener tag.
Symfony Messenger:
Use the bundle’s CurrencyConvertMessage to decouple conversions from controllers:
$message = new CurrencyConvertMessage($amount, 'USD', 'EUR');
$this->messageBus->dispatch($message);
Testing:
Mock the CurrencyConverter in tests:
$converter = $this->createMock(CurrencyConverter::class);
$converter->method('convert')->willReturn(100.00);
$this->container->set('lexik_currency.converter', $converter);
How can I help you explore Laravel packages today?