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

coverd/money-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require coverd/money-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Coverd\MoneyBundle\CoverdMoneyBundle::class => ['all' => true],
    ];
    
  2. Basic Configuration Edit config/packages/coverd_money.yaml:

    coverd_money:
        default_currency: 'EUR'
        currencies: ['EUR', 'USD', 'GBP']
    
  3. First Use Case Create a money value in a controller or service:

    use Money\Money;
    use Money\Currency;
    
    $amount = 100; // 100 cents (or 1.00 EUR)
    $currency = new Currency('EUR');
    $money = new Money($amount, $currency);
    
    // Or use the bundle's helper:
    $money = $this->get('coverd_money.factory')->create($amount, 'EUR');
    

Implementation Patterns

Core Workflows

  1. Money Creation Use the factory service for consistency:

    $factory = $this->get('coverd_money.factory');
    $money = $factory->create(100, 'USD'); // 1.00 USD
    
  2. Currency Conversion Inject the Coverd\MoneyBundle\Service\CurrencyConverter:

    $converter = $this->get('coverd_money.converter');
    $converted = $converter->convert($money, 'GBP'); // Converts to GBP
    
  3. Validation Validate money in forms using Symfony’s validator:

    # config/validator/validation.yaml
    Coverd\MoneyBundle\Validator\Constraints\Money:
        currency: EUR
        min: 0
        max: 100000
    
  4. Database Storage Store as cents (integer) + currency (string):

    $money->getAmount(); // 100 (cents)
    $money->getCurrency()->getCode(); // 'EUR'
    
  5. Twig Integration Use the money filter:

    {{ money(100, 'EUR') }} → "1.00 €"
    

Integration Tips

  • Doctrine ORM: Use MoneyType for entities:
    use Coverd\MoneyBundle\Doctrine\Types\MoneyType;
    
    /**
     * @ORM\Column(type="money")
     */
    private $price;
    
  • API Responses: Serialize with MoneyJsonEncoder:
    $encoder = $this->get('coverd_money.json_encoder');
    $json = $encoder->encode($money, 'json');
    
  • Commands: Use MoneyCommand for CLI tools:
    $this->get('coverd_money.command')->process($money);
    

Gotchas and Tips

Pitfalls

  1. Precision Handling

    • Always work in cents (integers) to avoid floating-point errors.
    • Example: 100 = 1.00 EUR, not 1.00 (which could become 0.999999).
  2. Currency Codes

    • Use ISO 4217 codes (e.g., USD, not US$).
    • Validate against config/packages/coverd_money.yaml currencies.
  3. Converter Dependencies

    • The bundle does not include exchange rates. Use a service like ExchangeRate-API or implement a custom converter.
  4. Symfony 6+ Compatibility

    • If using Symfony 6, ensure moneyphp/money is ^3.0. The bundle may lag behind.
  5. Doctrine Migrations

    • When adding MoneyType, run:
      php bin/console doctrine:migrations:diff
      

Debugging Tips

  • Dump Money Objects:
    dump($money->getAmount(), $money->getCurrency()->getCode());
    
  • Check Converter Rates:
    $converter->getRate('EUR', 'USD'); // Returns null if no rate set
    
  • Validator Errors:
    # config/packages/validator.yaml
    Coverd\MoneyBundle\Validator\Constraints\Money:
        message: "The amount must be between {{ min }} and {{ max }} {{ currency }}."
    

Extension Points

  1. Custom Converter Extend Coverd\MoneyBundle\Service\CurrencyConverter to fetch rates from an API:

    class ApiCurrencyConverter extends CurrencyConverter {
        public function getRate(string $from, string $to): ?float {
            $response = HttpClient::create()->request('GET', 'https://api.exchangerate-api.com/v4/latest/'.$from);
            return $response->toArray()['rates'][$to] ?? null;
        }
    }
    

    Register as a service:

    services:
        coverd_money.converter:
            class: App\Service\ApiCurrencyConverter
    
  2. Custom Money Type Override MoneyType for custom storage (e.g., JSON):

    class JsonMoneyType extends MoneyType {
        public function convertToDatabaseValue($value, AbstractPlatform $platform) {
            return json_encode([
                'amount' => $value->getAmount(),
                'currency' => $value->getCurrency()->getCode(),
            ]);
        }
    }
    
  3. Event Listeners Listen to coverd_money.pre_convert to modify conversions:

    $eventDispatcher->addListener('coverd_money.pre_convert', function (PreConvertEvent $event) {
        if ($event->getFrom()->getCurrency()->getCode() === 'EUR') {
            $event->setRate(1.1); // Force USD rate
        }
    });
    
  4. Testing Use MoneyTestCase for assertions:

    use Coverd\MoneyBundle\Tests\MoneyTestCase;
    
    class MyTest extends MoneyTestCase {
        public function testMoneyCreation() {
            $this->assertMoneyEquals(new Money(100, new Currency('EUR')), '100 EUR');
        }
    }
    
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