|
| 1 | +## Customizing events |
| 2 | + |
| 3 | +Sometimes you want to modify the standard events of a package. This is done quite simply. |
| 4 | + |
| 5 | +Let's add broadcast support? We need to implement our event from the interface. |
| 6 | + |
| 7 | +```php |
| 8 | +use Bavix\Wallet\Internal\Events\BalanceUpdatedEventInterface; |
| 9 | +use Illuminate\Contracts\Broadcasting\ShouldBroadcast; |
| 10 | + |
| 11 | +final class MyUpdatedEvent implements BalanceUpdatedEventInterface, ShouldBroadcast |
| 12 | +{ |
| 13 | + public function __construct( |
| 14 | + private \Bavix\Wallet\Models\Wallet $wallet, |
| 15 | + private DateTimeImmutable $updatedAt, |
| 16 | + ) {} |
| 17 | + |
| 18 | + public function getWalletId(): int { return $this->wallet->getKey(); } |
| 19 | + public function getWalletUuid(): string { return $this->wallet->uuid; } |
| 20 | + public function getBalance(): string { return $this->wallet->balanceInt; } |
| 21 | + public function getUpdatedAt(): DateTimeImmutable { return $this->updatedAt; } |
| 22 | + |
| 23 | + public function broadcastOn(): array |
| 24 | + { |
| 25 | + return $this->wallet->getAttributes(); |
| 26 | + } |
| 27 | +} |
| 28 | +``` |
| 29 | + |
| 30 | +The event is ready, but that's not all. Now you need to implement your assembler class, which will create an event inside the package. |
| 31 | + |
| 32 | +```php |
| 33 | +use Bavix\Wallet\Internal\Assembler\BalanceUpdatedEventAssemblerInterface; |
| 34 | + |
| 35 | +class MyUpdatedEventAssembler implements BalanceUpdatedEventAssemblerInterface |
| 36 | +{ |
| 37 | + public function create(\Bavix\Wallet\Models\Wallet $wallet) : \Bavix\Wallet\Internal\Events\BalanceUpdatedEventInterface |
| 38 | + { |
| 39 | + return new MyUpdatedEvent($wallet, new DateTimeImmutable()); |
| 40 | + } |
| 41 | +} |
| 42 | +``` |
| 43 | + |
| 44 | +Next, go to the package settings (wallet.php). |
| 45 | +We change the event to a new one. |
| 46 | + |
| 47 | +```php |
| 48 | + 'assemblers' => [ |
| 49 | + 'balance_updated_event' => MyUpdatedEventAssembler::class, |
| 50 | + ], |
| 51 | +``` |
| 52 | + |
| 53 | +Then everything is the same as with the standard events of the package. |
| 54 | + |
| 55 | +```php |
| 56 | +use Bavix\Wallet\Internal\Events\BalanceUpdatedEventInterface; |
| 57 | + |
| 58 | +protected $listen = [ |
| 59 | + BalanceUpdatedEventInterface::class => [ |
| 60 | + MyBalanceUpdatedListener::class, |
| 61 | + ], |
| 62 | +]; |
| 63 | +``` |
| 64 | + |
| 65 | +And then we create a listener. |
| 66 | + |
| 67 | +```php |
| 68 | +use Bavix\Wallet\Internal\Events\BalanceUpdatedEventInterface; |
| 69 | + |
| 70 | +class MyBalanceUpdatedListener |
| 71 | +{ |
| 72 | + public function handle(BalanceUpdatedEventInterface $event): void |
| 73 | + { |
| 74 | + // And then the implementation... |
| 75 | + } |
| 76 | +} |
| 77 | +``` |
| 78 | + |
| 79 | +It worked! |
0 commit comments