Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Currency Bundle Laravel Package

dotdev/currency-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require dotdev/currency-bundle
    

    Enable it in config/bundles.php:

    return [
        // ...
        Dotdev\CurrencyBundle\DotdevCurrencyBundle::class => ['all' => true],
    ];
    
  2. Configuration Define currencies in config/packages/dotdev_currency.yaml:

    dotdev_currency:
        base_currency: 'USD'
        currencies:
            USD: {name: 'US Dollar', symbol: '$'}
            EUR: {name: 'Euro', symbol: '€'}
    
  3. 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());
    }
    

Implementation Patterns

Core Workflows

  1. 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
    
  2. Dynamic Currency Handling Attach currencies to entities (e.g., Order, Product) via traits:

    use Dotdev\CurrencyBundle\Currency\CurrencyAwareTrait;
    
    class Order implements CurrencyAwareInterface
    {
        use CurrencyAwareTrait;
        // ...
    }
    
  3. API Integration Serialize currencies in API responses:

    use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
    
    $normalizer = new ObjectNormalizer();
    $normalizer->setIgnoredAttributes(['currencyCode']);
    $serialized = $normalizer->normalize($order);
    

Integration Tips

  • Doctrine ORM: Use CurrencyType for database fields:
    use Dotdev\CurrencyBundle\Doctrine\DBAL\Types\CurrencyType;
    
    $builder->addColumn('price', CurrencyType::CURRENCY);
    
  • Symfony Forms: Bind currencies to form fields:
    $builder->add('currency', CurrencyType::class, [
        'choices' => $currencyRepository->getAll(),
    ]);
    
  • Event Listeners: React to currency changes (e.g., update exchange rates):
    $eventDispatcher->addListener(
        CurrencyEvents::RATE_UPDATED,
        [$this, 'onRateUpdated']
    );
    

Gotchas and Tips

Pitfalls

  1. Base Currency Dependency

    • All conversions rely on the base_currency setting. Ensure it’s correctly configured in dotdev_currency.yaml.
    • Debug Tip: Use dump($converter->getBaseCurrency()) to verify.
  2. Caching Exchange Rates

    • The bundle doesn’t cache rates by default. For performance, implement a cache layer:
      $converter->setCache($cachePool); // Inject Symfony Cache component
      
  3. Entity Lifecycle

    • If using CurrencyAwareTrait, ensure setCurrency() is called before saving entities to avoid null values.
  4. Archived Status

    • The package is archived (no active maintenance). Test thoroughly in staging before production use.

Debugging

  • Invalid Currency Codes
    • Throws CurrencyNotFoundException. Validate codes against CurrencyRepository::getAll().
  • Rate Updates
    • Log CurrencyEvents::RATE_UPDATED to track dynamic changes:
      $logger->info('Rate updated', ['from' => $event->getFrom(), 'to' => $event->getTo()]);
      

Extension Points

  1. 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 { ... }
    
  2. Validation Add constraints to currency fields:

    use Dotdev\CurrencyBundle\Validator\Constraints\ValidCurrency;
    
    $builder->add('currency', CurrencyType::class, [
        'constraints' => [new ValidCurrency()]
    ]);
    
  3. 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) }}
  • Fallback Rates: Set default rates in config:
    dotdev_currency:
        default_rates:
            USD: {EUR: 0.8553, GBP: 0.7344}
    
  • Legacy Systems: Bridge with old currency codes via a custom CurrencyNormalizer.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor