Broadcastable event shouldnt be a JsonSerializable everytime

This commit is contained in:
2026-02-27 01:14:21 +04:00
parent b81223a550
commit 6b044074ce
3 changed files with 10 additions and 10 deletions

View File

@@ -33,8 +33,9 @@ return [
### 1. Creating regular events for publishing to a RabbitMQ ### 1. Creating regular events for publishing to a RabbitMQ
Create an event that implements the `Broadcast` interface. `Broadcast` interface Create an event that implements the `Broadcast` interface.
extends `JsonSerializable` then your event should implements `jsonSerialize` method. Your event should implements `JsonSerializable` interface if
default serializer is used.
```php ```php
namespace App\Events; namespace App\Events;
@@ -42,8 +43,9 @@ namespace App\Events;
use Diffhead\PHP\LaravelRabbitMQ\Event\Broadcast; use Diffhead\PHP\LaravelRabbitMQ\Event\Broadcast;
use Diffhead\PHP\LaravelRabbitMQ\Trait\BroadcastEvent; use Diffhead\PHP\LaravelRabbitMQ\Trait\BroadcastEvent;
use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Foundation\Events\Dispatchable;
use JsonSerializable;
class UserCreated implements Broadcast class UserCreated implements Broadcast, JsonSerializable
{ {
use Dispatchable, BroadcastEvent; use Dispatchable, BroadcastEvent;

View File

@@ -4,9 +4,7 @@ declare(strict_types=1);
namespace Diffhead\PHP\LaravelRabbitMQ\Event; namespace Diffhead\PHP\LaravelRabbitMQ\Event;
use JsonSerializable; interface Broadcast
interface Broadcast extends JsonSerializable
{ {
public function getConnection(): string; public function getConnection(): string;
public function getQueue(): string; public function getQueue(): string;

View File

@@ -11,16 +11,16 @@ use PhpAmqpLib\Message\AMQPMessage;
class Serializer implements SerializerInterface class Serializer implements SerializerInterface
{ {
public function serialize(object $data): AMQPMessage public function serialize(object $event): AMQPMessage
{ {
if ($data instanceof JsonSerializable) { if ($event instanceof JsonSerializable) {
return new AMQPMessage( return new AMQPMessage(
json_encode($data->jsonSerialize()) json_encode($event->jsonSerialize())
); );
} }
throw new InvalidArgumentException( throw new InvalidArgumentException(
'Data should be an instance of BroadcastEvent' 'Event should be an instance of JsonSerializable'
); );
} }
} }