|
101 | 101 | <x-currency currency="USD" />
|
102 | 102 | ```
|
103 | 103 |
|
| 104 | +### Macros |
| 105 | + |
| 106 | +This package implements the Laravel `Macroable` trait, allowing macros and mixins on both `Money` and `Currency`. |
| 107 | + |
| 108 | +Example use case: |
| 109 | + |
| 110 | +```php |
| 111 | +use Akaunting\Money\Currency; |
| 112 | +use Akaunting\Money\Money; |
| 113 | + |
| 114 | +Money::macro( |
| 115 | + 'absolute', |
| 116 | + fn () => $this->isPositive() ? $this : $this->multiply(-1) |
| 117 | +); |
| 118 | + |
| 119 | +$money = Money::USD(1000)->multiply(-1); |
| 120 | + |
| 121 | +$absolute = $money->absolute(); |
| 122 | +``` |
| 123 | + |
| 124 | +Macros can be called statically too: |
| 125 | + |
| 126 | +```php |
| 127 | +use Akaunting\Money\Currency; |
| 128 | +use Akaunting\Money\Money; |
| 129 | + |
| 130 | +Money::macro('zero', fn (?string $currency = null) => new Money(0, new Currency($currency ?? 'GBP'))); |
| 131 | + |
| 132 | +$money = Money::zero(); |
| 133 | +``` |
| 134 | + |
| 135 | +### Mixins |
| 136 | + |
| 137 | +Along with Macros, Mixins are also supported. This allows merging another classes methods into the Money or Currency class. |
| 138 | + |
| 139 | +Define the mixin class: |
| 140 | + |
| 141 | +```php |
| 142 | +use Akaunting\Money\Money; |
| 143 | + |
| 144 | +class CustomMoney |
| 145 | +{ |
| 146 | + public function absolute(): Money |
| 147 | + { |
| 148 | + return $this->isPositive() ? $this : $this->multiply(-1); |
| 149 | + } |
| 150 | + |
| 151 | + public static function zero(?string $currency = null): Money |
| 152 | + { |
| 153 | + return new Money(0, new Currency($currency ?? 'GBP')); |
| 154 | + } |
| 155 | +} |
| 156 | +``` |
| 157 | + |
| 158 | +Register the mixin, by passing an instance of the class: |
| 159 | + |
| 160 | +```php |
| 161 | +Money::mixin(new CustomMoney); |
| 162 | +``` |
| 163 | + |
| 164 | +The methods from the custom class will be available: |
| 165 | + |
| 166 | +```php |
| 167 | +$money = Money::USD(1000)->multiply(-1); |
| 168 | +$absolute = $money->absolute(); |
| 169 | + |
| 170 | +// Static methods via mixins are supported too: |
| 171 | +$money = Money::zero(); |
| 172 | +``` |
| 173 | + |
104 | 174 | ## Changelog
|
105 | 175 |
|
106 | 176 | Please see [Releases](../../releases) for more information on what has changed recently.
|
|
0 commit comments