Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Serialization Laravel Package

simple-bus/serialization

Generic PHP interfaces and classes for serializing SimpleBus message objects, supporting consistent message encoding/decoding for transport and storage. Part of the SimpleBus ecosystem; documentation and issues are maintained in the main SimpleBus repository.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require simple-bus/serialization
    

    Add to composer.json if using SimpleBus MessageBus:

    "require": {
        "simple-bus/serialization": "^6.0"
    }
    
  2. First Use Case: Serialize a message into an envelope for transport (e.g., to a queue or HTTP API):

    use SimpleBus\Serializer\MessageInEnvelopeSerializer;
    use SimpleBus\Serializer\MessageInEnvelopeSerializerInterface;
    
    $serializer = new MessageInEnvelopeSerializer();
    $envelope = $serializer->serialize($message, $messageName);
    
  3. Deserialization:

    $deserialized = $serializer->deserialize($envelope);
    
  4. Key Classes:

    • MessageInEnvelopeSerializer: Core serializer for messages.
    • MessageInEnvelopeSerializerInterface: Contract for custom implementations.
    • MessageInEnvelope: Represents a serialized message with metadata.

Where to Look First

  • Documentation: Official guide for interfaces, implementations, and edge cases.
  • src/MessageInEnvelope.php: Core envelope structure.
  • src/MessageInEnvelopeSerializer.php: Default implementation (uses json_encode/json_decode by default).

Implementation Patterns

Workflows

1. Message Transport (Queue/HTTP)

  • Serialize:
    $envelope = $serializer->serialize(
        $command = new PlaceOrder($orderId, $items),
        'App\Command\PlaceOrder'
    );
    
  • Transport: Send $envelope to a queue (e.g., Redis, RabbitMQ) or HTTP endpoint.
  • Deserialize:
    $envelope = json_decode($rawEnvelope, true); // If transported as JSON
    $deserialized = $serializer->deserialize($envelope);
    

2. Custom Serialization

Extend MessageInEnvelopeSerializer for non-JSON formats (e.g., XML, Protocol Buffers):

class XmlMessageSerializer implements MessageInEnvelopeSerializerInterface {
    public function serialize($message, string $messageName): MessageInEnvelope {
        $xml = $this->messageToXml($message);
        return new MessageInEnvelope($messageName, $xml);
    }

    public function deserialize(MessageInEnvelope $envelope): object {
        return $this->xmlToMessage($envelope->getMessage());
    }
}

3. Integration with SimpleBus

Use with SimpleBus\MessageBus\MessageBus for decoupled messaging:

$bus = new MessageBus([
    new QueueBus([
        new RedisQueue(),
        new SerializingMessageConverter($serializer),
    ]),
]);

Integration Tips

  • Dependency Injection: Bind the serializer to your container (e.g., Laravel’s AppServiceProvider):
    $this->app->singleton(MessageInEnvelopeSerializerInterface::class, function ($app) {
        return new MessageInEnvelopeSerializer();
    });
    
  • Middleware: Add validation/logging around serialization:
    $serializer->serialize($message, $messageName);
    $this->log->info("Serialized message: {$messageName}");
    
  • Testing: Mock MessageInEnvelopeSerializerInterface for unit tests:
    $mockSerializer = $this->createMock(MessageInEnvelopeSerializerInterface::class);
    $mockSerializer->method('serialize')->willReturn(new MessageInEnvelope('Test', []));
    

Gotchas and Tips

Pitfalls

  1. Message Name Mismatch:

    • Issue: Deserialization fails if $messageName in MessageInEnvelope doesn’t match the expected class.
    • Fix: Validate $envelope->getMessageName() before deserializing or use a factory pattern.
  2. Circular References:

    • Default JSON serializer fails on circular references (e.g., OrderCustomer).
    • Solution: Use JsonSerializable or a custom serializer with JSON_THROW_ON_ERROR.
  3. PHP 8.0+ Strict Types:

    • Issue: Older code may throw TypeError if return types aren’t strict.
    • Fix: Update method signatures to use object return types or generics (if using PHP 8.1+).
  4. Performance:

    • Serializing large objects (e.g., DTOs with arrays) can be slow.
    • Tip: Use serialize()/unserialize() for PHP-native objects or Protocol Buffers for binary formats.

Debugging

  • Inspect Envelopes:
    var_dump($envelope->getMessageName(), $envelope->getMessage());
    
  • Check Serializer Output:
    $serialized = $serializer->serialize($message, 'Test');
    file_put_contents('debug.json', json_encode($serialized->getMessage()));
    
  • Enable JSON Errors:
    json_encode($data, JSON_THROW_ON_ERROR); // For strict validation
    

Extension Points

  1. Custom Serializers: Implement MessageInEnvelopeSerializerInterface for domain-specific formats (e.g., Avro, MessagePack):

    class AvroSerializer implements MessageInEnvelopeSerializerInterface {
        public function serialize($message, string $messageName): MessageInEnvelope {
            $avroData = $this->avroEncode($message);
            return new MessageInEnvelope($messageName, $avroData);
        }
        // ...
    }
    
  2. Metadata Handling: Extend MessageInEnvelope to include headers/metadata:

    class ExtendedEnvelope extends MessageInEnvelope {
        public function __construct(
            string $messageName,
            $message,
            array $headers = []
        ) {
            parent::__construct($messageName, $message);
            $this->headers = $headers;
        }
    }
    
  3. Laravel Integration:

    • Service Provider:
      $this->app->bind(MessageInEnvelopeSerializerInterface::class, function () {
          return new MessageInEnvelopeSerializer(new JsonEncoder());
      });
      
    • Queue Jobs:
      class SendEmailJob implements ShouldQueue {
          use Dispatchable, InteractsWithQueue;
      
          public function handle() {
              $serializer = app(MessageInEnvelopeSerializerInterface::class);
              $envelope = $serializer->serialize(new SendEmail($email), SendEmail::class);
              // Store $envelope in DB/Redis for later processing
          }
      }
      

Config Quirks

  • Default JSON Encoder: The default serializer uses json_encode() with JSON_THROW_ON_ERROR (PHP 7.3+). For older PHP, add:
    $serializer = new MessageInEnvelopeSerializer(new JsonEncoder(JSON_THROW_ON_ERROR));
    
  • Namespace Handling: Ensure $messageName uses fully qualified class names (e.g., App\Command\PlaceOrder), not short names.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky