Extend Money and Currency with Macros and Mixins
masterBoth Money and Currency implement the Macroable trait, allowing you to add custom functionality at runtime.
Macros: Use Money::macro('name', callback) to add a new method. Macros can be called on instances or statically.
Mixins: Use Money::mixin($instance) to merge all methods from a custom class into the Money class. This is useful for grouping related custom logic.
Example using a Mixin:
class CustomMoney {
public function absolute(): Money {
return $this->isPositive() ? $this : $this->multiply(-1);
}
}
Money::mixin(new CustomMoney);
$money = Money::USD(1000)->multiply(-1);
echo $money->absolute();use Akaunting\Money\Money;
// Registering a Macro
Money::macro('zero', fn (?string $currency = null) => new Money(0, new Currency($currency ?? 'GBP')));
$money = Money::zero();