Sons of PHP
Source Code
  • 🏠Home
  • Contributor Covenant Code of Conduct
  • Getting Help
  • Reporting Issues
  • Security Policy
  • 🪈Bard
    • Overview
    • Commands
  • Symfony Bundles
    • Feature Toggle
  • Contracts
    • Contracts Overview
    • Common
    • Cookie
    • CQRS
    • Filesystem
    • Mailer
    • Pager
    • Registry
    • State Machine
  • 📦Components
    • Assert
    • Cache
      • Adapters
      • Marshallers
    • Clock
    • Container
    • Cookie
    • CQRS
    • Event Dispatcher
    • Event Sourcing
      • Aggregates
        • Aggregate Repository
      • Event Messages
        • Using the Serializable Event Message
        • Message Enrichers
        • Message Serializers
        • Message Repository
        • Message Upcasters
    • Feature Toggle
    • Filesystem
      • Adapters
    • Http Factory
    • Http Handler
    • Http Message
    • JSON
    • Link
    • Logger
      • Handlers
      • Enrichers
      • Filters
      • Formatters
    • Mailer
      • Transports
    • Money
      • Currency Providers
      • Operators
      • Queries
    • Pager
      • Adapters
    • Registry
    • State Machine
    • Version
  • 💁Contributing
    • Contributing Overview
    • Contributing Code
    • Discussions
    • Documentation
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub
  1. Components
  2. Money

Operators

Operators allow you to change something about the Money and will return a new instance of the Money. For example, the methods: add, subtract, multiply, and divide on the Money class are all MoneyOperators.

You can create your own Money Operators and use them with the Money class out of the box.

<?php
$operator = new MyOwnMoneyOperator();
$newMoney = $money->with($operator);

Here's how it works in slightly more detail.

<?php
use SonsOfPHP\Component\Money\Operator\Money\AddMoneyOperator;
use SonsOfPHP\Component\Money\Money;

$accountBalance = Money::USD(1000);
$depositAmount  = Money::USD(2000);

// The construct takes the deposit amount we will apply to the balance
$operator = new AddMoneyOperator($depositAmount);

// The operator will apply (the deposit amount) to the account balance
// and the returned MoneyInterface will be a new object
$newBalance = $operator->apply($accountBalance);

$newBalance->isEqualTo($accountBalance); // will return false

// Another way to use the Operator is
$anotherNewBalance = $accountBalance->with($operator);

$newBalance->isEqualTo($anotherNewBalance); // will return true

// Even though $newBalance and $anotherNewBalance are different objects, they
// are both USD and both have the same amount (3000)

As you can see, using Operators provides you some power. You could create your Operator to calculate a payment amount for a loan. Another great idea is to use an Operator that can calculate tax.

PreviousCurrency ProvidersNextQueries

Last updated 8 months ago

Was this helpful?

📦