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

Money Bundle Laravel Package

clippings/money-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require tbbc/money-bundle
    

    Add to AppKernel.php (Symfony 2.x) or config/bundles.php (Symfony 3.x):

    new Tbbc\MoneyBundle\TbbcMoneyBundle(),
    
  2. First Use Case: Create a Money object directly via the underlying library:

    use Money\Money;
    
    $amount = Money::USD(1000); // 10.00 USD
    
  3. Form Integration: Use the provided MoneyType for Symfony forms:

    use Tbbc\MoneyBundle\Form\Type\MoneyType;
    
    $builder->add('price', MoneyType::class, [
        'currency' => 'EUR',
        'scale' => 2,
    ]);
    
  4. Configuration: Override default settings in config/packages/tbbc_money.yaml (Symfony 3.x+):

    tbbc_money:
        default_currency: 'USD'
        default_scale: 2
    

Implementation Patterns

Core Workflows

  1. Domain Modeling: Use Money objects in entities to enforce type safety:

    class Order {
        private $total;
    
        public function __construct(Money $total) {
            $this->total = $total;
        }
    
        public function addItem(Money $itemPrice): void {
            $this->total = $this->total->add($itemPrice);
        }
    }
    
  2. Form Handling: Bind form submissions to Money objects:

    $form = $this->createForm(MoneyType::class, $order->getTotal());
    if ($form->isSubmitted() && $form->isValid()) {
        $order->setTotal($form->getData());
    }
    
  3. Currency Conversion: Use the Money library's built-in conversion:

    $usd = Money::USD(1000);
    $eur = $usd->convert('EUR'); // Requires exchange rates configured
    
  4. Validation: Leverage Symfony's validation with custom constraints:

    use Tbbc\MoneyBundle\Validator\Constraints as MoneyAssert;
    
    /**
     * @MoneyAssert\Positive()
     */
    private $amount;
    

Integration Tips

  • Doctrine ORM: Use Money as a custom type via AttributeConverter (Symfony 3.4+):

    #[ORM\ConvertToManaged]
    #[ORM\Column(type: 'string')]
    private $amountAsString;
    
    #[ORM\ConvertFromManaged]
    public function getAmount(): Money {
        return Money::USD(intval($this->amountAsString));
    }
    
  • API Responses: Serialize Money objects to JSON:

    #[Serializer\SerializedName('total')]
    public function getTotalAsString(): string {
        return $this->total->getAmount() . ' ' . $this->total->getCurrency();
    }
    
  • Testing: Mock Money objects for unit tests:

    $this->createMock(Money::class)
         ->method('add')
         ->willReturn(Money::USD(2000));
    

Gotchas and Tips

Pitfalls

  1. Archived Status:

    • The bundle is archived (last release in 2018). Verify compatibility with modern Symfony/Laravel (if using via bridge).
    • Fork or patch if critical bugs arise (e.g., PHP 8.x support).
  2. Currency Conversion:

    • The underlying money library does not include exchange rates. You must:
      • Use a third-party service (e.g., moneyphp/money with league/iso3166).
      • Manually configure rates in a service:
        $converter = new Money\Converter([
            'USD' => ['EUR' => 0.85],
            'EUR' => ['USD' => 1.18],
        ]);
        
  3. Form Type Quirks:

    • MoneyType expects scale (decimal places) to match the Money object’s precision.
    • Default scale is 2; override in config or per-field:
      # config/packages/tbbc_money.yaml
      tbbc_money:
          default_scale: 4  # For cents in some currencies
      
  4. Doctrine Integration:

    • No built-in Doctrine DBAL type. Use a custom type or serialize to string:
      #[ORM\Column(type: 'text')]
      private $amountJson;
      
      public function getAmount(): Money {
          return Money::fromJson($this->amountJson);
      }
      
  5. Symfony 5+ Deprecations:

    • If using Symfony 5+, replace AppKernel with config/bundles.php.
    • Use autoconfigure: true in config/packages/framework.yaml for auto-wiring.

Debugging Tips

  1. Validation Errors:

    • Check for mismatched currency or scale between form and entity.
    • Enable Symfony’s profiler to inspect form errors.
  2. Serialization Issues:

    • Ensure Money objects are converted to strings/arrays for JSON/API responses:
      $money->getAmount() . ' ' . $money->getCurrency();
      
  3. Exchange Rate Logic:

    • Log conversion failures:
      try {
          $converted = $money->convert('EUR');
      } catch (Money\UnknownCurrencyException $e) {
          $this->logger->error('Unsupported currency', ['currency' => $money->getCurrency()]);
      }
      

Extension Points

  1. Custom Money Types: Extend the bundle to support additional currencies or validation rules:

    class CustomMoneyType extends MoneyType {
        public function configureOptions(OptionsResolver $resolver) {
            $resolver->setDefaults([
                'currency' => 'GBP', // Default to GBP
            ]);
        }
    }
    
  2. Event Listeners: Add logic for money operations (e.g., tax calculation):

    $dispatcher->addListener('order.created', function (OrderEvent $event) {
        $event->getOrder()->setTax($event->getOrder()->getTotal()->multiply(0.20));
    });
    
  3. API Platform: If using API Platform, create a custom MoneyOutput:

    #[ApiResource]
    class Order {
        #[Groups(['order:read'])]
        public function getTotalAsString(): string {
            return $this->total->getAmount() . ' ' . $this->total->getCurrency();
        }
    }
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware