AymDev / MessengerAzureBundle

A Symfony 4/5/6 bundle providing a Messenger transport for Azure Service Bus using the Azure REST API.
MIT License
10 stars 7 forks source link

Examples for serializer services in documentation #2

Closed akserikawa closed 2 years ago

akserikawa commented 2 years ago

@AymDev @joker806 Could you provide a basic example of a valid serializer service for messages in a queue/topic in the README? It would be helpful for a quick start

AymDev commented 2 years ago

Sorry for the response delay. I don't think that this kind of example would be relevant in the documentation as it is purely related to how Messenger works. Check the documentation which links to the SerializerInterface

But here is a dummy example:

<?php

namespace App\Messenger\MyQueueOrTopic;

use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Transport\Serialization\SerializerInterface;

class MyQueueOrTopicSerializer implements SerializerInterface
{
    /**
     * @param mixed[]|array{body: string, headers: array<string, array<int, string>>} $encodedEnvelope
     */
    public function decode(array $encodedEnvelope): Envelope
    {
        $data = json_decode($encodedEnvelope['body']);
        $message = new MyQueueOrTopicMessage($data);
        return new Envelope($message);
    }

    /**
     * @return mixed[]
     */
    public function encode(Envelope $envelope): array
    {
        /** @var MyQueueOrTopicMessage $message */
        $message = $envelope->getMessage();
        $data = $message->getData();
        return [
            'body' => json_encode($data),
        ];
    }
}

I'd also use the Symfony Serializer component instead of the json_* functions, that can help to encode/decode to DTO, etc.

akserikawa commented 2 years ago

Thanks for the example! Managed to get it working a while ago. Indeed, it's just a matter of understanding the serialization/deserialization workflow.