Ecotone
SponsorBlogGithubSupport and ContactCommunity Channel
  • About
  • Installation
  • How to use
    • CQRS PHP
    • Event Handling PHP
    • Aggregates & Sagas
    • Scheduling in PHP
    • Asynchronous PHP
    • Event Sourcing PHP
    • Microservices PHP
    • Resiliency and Error Handling
    • Laravel Demos
    • Symfony Demos
      • Doctrine ORM
  • Tutorial
    • Before we start tutorial
    • Lesson 1: Messaging Concepts
    • Lesson 2: Tactical DDD
    • Lesson 3: Converters
    • Lesson 4: Metadata and Method Invocation
    • Lesson 5: Interceptors
    • Lesson 6: Asynchronous Handling
  • Enterprise
  • Modelling
    • Introduction
    • Message Bus and CQRS
      • CQRS Introduction - Commands
        • Query Handling
        • Event Handling
      • Aggregate Introduction
        • Aggregate Command Handlers
        • Aggregate Query Handlers
        • Aggregate Event Handlers
        • Advanced Aggregate creation
      • Repositories Introduction
      • Business Interface
        • Introduction
        • Business Repository
        • Database Business Interface
          • Converting Parameters
          • Converting Results
      • Saga Introduction
      • Identifier Mapping
    • Extending Messaging (Middlewares)
      • Message Headers
      • Interceptors (Middlewares)
        • Additional Scenarios
      • Intercepting Asynchronous Endpoints
      • Extending Message Buses (Gateways)
    • Event Sourcing
      • Installation
      • Event Sourcing Introduction
        • Working with Event Streams
        • Event Sourcing Aggregates
          • Working with Aggregates
          • Applying Events
          • Different ways to Record Events
        • Working with Metadata
        • Event versioning
        • Event Stream Persistence
          • Event Sourcing Repository
          • Making Stream immune to changes
          • Snapshoting
          • Persistence Strategies
          • Event Serialization and PII Data (GDPR)
      • Projection Introduction
        • Configuration
        • Choosing Event Streams for Projection
        • Executing and Managing
          • Running Projections
          • Projection CLI Actions
          • Access Event Store
        • Projections with State
        • Emitting events
    • Recovering, Tracing and Monitoring
      • Resiliency
        • Retries
        • Error Channel and Dead Letter
          • Dbal Dead Letter
        • Idempotent Consumer (Deduplication)
        • Resilient Sending
        • Outbox Pattern
        • Concurrency Handling
      • Message Handling Isolation
      • Ecotone Pulse (Service Dashboard)
    • Asynchronous Handling and Scheduling
      • Asynchronous Message Handlers
      • Asynchronous Message Bus (Gateways)
      • Delaying Messages
      • Time to Live
      • Message Priority
      • Scheduling
      • Dynamic Message Channels
    • Distributed Bus and Microservices
      • Distributed Bus
        • Distributed Bus with Service Map
          • Configuration
          • Custom Features
          • Non-Ecotone Application integration
          • Testing
        • AMQP Distributed Bus (RabbitMQ)
          • Configuration
        • Distributed Bus Interface
      • Message Consumer
      • Message Publisher
    • Business Workflows
      • The Basics - Stateless Workflows
      • Stateful Workflows - Saga
      • Handling Failures
    • Testing Support
      • Testing Messaging
      • Testing Aggregates and Sagas with Message Flows
      • Testing Event Sourcing Applications
      • Testing Asynchronous Messaging
  • Messaging and Ecotone In Depth
    • Overview
    • Multi-Tenancy Support
      • Getting Started
        • Any Framework Configuration
        • Symfony and Doctrine ORM
        • Laravel
      • Different Scenarios
        • Hooking into Tenant Switch
        • Shared and Multi Database Tenants
        • Accessing Current Tenant in Message Handler
        • Events and Tenant Propagation
        • Multi-Tenant aware Dead Letter
      • Advanced Queuing Strategies
    • Document Store
    • Console Commands
    • Messaging concepts
      • Message
      • Message Channel
      • Message Endpoints/Handlers
        • Internal Message Handler
        • Message Router
        • Splitter
      • Consumer
      • Messaging Gateway
      • Inbound/Outbound Channel Adapter
    • Method Invocation And Conversion
      • Method Invocation
      • Conversion
        • Payload Conversion
        • Headers Conversion
    • Service (Application) Configuration
    • Contributing to Ecotone
      • How Ecotone works under the hood
      • Ecotone Phases
      • Registering new Module Package
      • Demo Integration with SQS
        • Preparation
        • Inbound and Outbound Adapters and Message Channel
        • Message Consumer and Publisher
  • Modules
    • Overview
    • Symfony
      • Symfony Configuration
      • Symfony Database Connection (DBAL Module)
      • Doctrine ORM
      • Symfony Messenger Transport
    • Laravel
      • Laravel Configuration
      • Database Connection (DBAL Module)
      • Eloquent
      • Laravel Queues
      • Laravel Octane
    • Ecotone Lite
      • Logging
      • Database Connection (DBAL Module)
    • JMS Converter
    • OpenTelemetry (Tracing and Metrics)
      • Configuration
    • RabbitMQ Support
    • Kafka Support
      • Configuration
      • Message partitioning
      • Usage
    • DBAL Support
    • Amazon SQS Support
    • Redis Support
  • Other
    • Contact, Workshops and Support
Powered by GitBook
On this page
  • Installation
  • Module Powered By
  • Native Conversion
  • Array Deserialization
  • Custom Conversions To Classes
  • Example usage
  • Custom Conversions from Classes
  • Serialization Customization
  • Configuration
  • withDefaultNullSerialization
  • withNamingStrategy
  • withDefaultEnumSupport
  • Serialize Nulls for specific conversion
  • Conversion Table

Was this helpful?

Export as PDF
  1. Modules

JMS Converter

PHP Converters Serializers Deserializers

PreviousDatabase Connection (DBAL Module)NextOpenTelemetry (Tracing and Metrics)

Last updated 2 months ago

Was this helpful?

Installation

composer require ecotone/jms-converter

Ecotone comes with integration with and extending it with extra features.

Module Powered By

Great library, which allow for advanced conversion between types .

Native Conversion

Ecotone with JMS will do it's best to deserialize your classes without any additional configuration needed. Suppose we have JSON like below:

{
    "personName": "Johny",
    "address": ["street": "A Good One", "houseNumber": 123
}
$this->commandBus->sendWithRouting(
   "settings.change", 
   '{"personName": "Johny","address":["street":"A Good One","houseNumber":123}',
   "application/json"
)

Then, suppose we have endpoint with following Command:

#[CommandHandler]
public function changeSettings(ChangeSettings $command)
{
   // do something
}
class ChangeSettings
{
    private string $personName;    
    private Address $address;
}

class Address
{
    private string $street;
    private string $houseNumber;
}

No need for any configuration, deserialization and serialization will be handled for you.

Array Deserialization

In order to deserialize array you must provide type hint.

/**
* @var Product[]
*/
private array $products;

This will let JMS know, how to deserialize given array. In order to deserialize array of scalar types:

/** @var string[] */
private array $productNames;
=>
["milk","plate"]

If your array is hash map however:

/** @var array<string,string> */
private array $order;
=>
["productId":"fff123a","productName":"milk"]

If you've mixed array containing scalars, then you may use ArrayObject to deserialize and serialize it preserving keys and types.

private \ArrayObject $data;
=>
["name":"Johny","age":13,"passport":["id":123]]

Custom Conversions To Classes

The difference between Native Conversion is that you take control of deserialization mechanism for specific class. You may call factory method, which will validate correctness of the data or you may provide some default based on your business logic. Besides you may find it useful when there is a need to make conversion from class to simple type like string or int.

Example usage

If we want to call bus with given JSON and deserialize productIds to UUID:

{
    "productIds": ["104c69ac-af3d-44d1-b2fa-3ecf6b7a3558"], 
    "promotionCode": "33dab", 
    "quickDelivery": false
}
$this->commandBus->sendWithRouting(
   "order.place",  
   '{"productIds": ["104c69ac-af3d-44d1-b2fa-3ecf6b7a3558"], "promotionCode": "33dab", "quickDelivery": false}',
   "application/json"
)

Then, suppose we have endpoint with following Command:

#[CommandHandler]
public function placeOrder(PlaceOrder $command)
{
   // do something
}
class PlaceOrder
{
    /**
     * @var Uuid[]
     */
    private array $productIds;
    
    private ?string $promotionCode;
    
    private bool $quickDelivery;
}

We do not need to add any metadata describing how to convert JSON to PlaceOrder PHP class. We already have it using type hints.

The only thing, that we need is to add how to convert string to UUID. We do it using Converter:

class ExampleConverterService
{
    #[Converter]
    public function convert(string $data) : Uuid
    {
        return Uuid::fromString($data);
    }
}

And that's enough. Whenever we will use string to UUID conversion or string[] to UUID[]. This converter will be automatically used.

Custom Conversions from Classes

Above example was for deserialization, however if you want to make use of serialization, then Converter from UUID to string is needed.

class ExampleConverterService
{
    #[Converter]
    public function convert(Uuid $data) : string
    {
        return $data->toString();
    }
}
class PlaceOrder
{
    /**
     * @var Uuid[]
     */
    private array $productIds;
    
    private ?string $promotionCode;
    
    private bool $quickDelivery;
}

$this->serializer->convertFromPHP(
    new PlaceOrder(//construct), 
    "application/json"
)

=>

{"productIds": ["104c69ac-af3d-44d1-b2fa-3ecf6b7a3558"], "promotionCode": "33dab", "quickDelivery": false}

Serialization Customization

class GetOrder
{
   /**
   * @SerializedName("order_id")
   */
   private string $orderId;
}

Configuration

class Configuration
{
    #[ServiceContext]
    public function getJmsConfiguration()
    {
        return JMSConverterConfiguration::createWithDefaults()
                ->withDefaultNullSerialization(false) // 1
                ->withNamingStrategy("identicalPropertyNamingStrategy"); // 2
                ->withDefaultEnumSupport(true) // 3
    }
}

withDefaultNullSerialization

Should nulls be serialized (default: false)

withNamingStrategy

Serialization naming strategy ("identicalPropertyNamingStrategy"/"camelCasePropertyNamingStrategy", default: "identicalPropertyNamingStrategy")

withDefaultEnumSupport

When enabled, default enum converter will be used, therefore Enums will serialize to simple types (default: false)

Serialize Nulls for specific conversion

$this->serializer->convertFromPHP(
    ["id" => 1,"name" => null], 
    "application/json;serializeNull=true"
)

=>

{"id":1,"name":null}

Conversion Table

JMS Converter can handle conversions:

// conversion from JSON to PHP
application/json => application/x-php | {"productId": 1} => new OrderProduct(1)
// conversion from PHP to JSON
application-x-php => application/json | new OrderProduct(1) => {"productId": 1}

// conversion from XML to PHP
application/xml => application/x-php | <productId>1</productId> => new OrderProduct(1)
// conversion from PHP to XML
application-x-php => application/xml | new OrderProduct(1) => <productId>1</productId>

// conversion from JSON to PHP Array
application/json => application/x-php;type=array | {"productId": 1} => ["productId": 1]
// conversion from PHP Array to JSON
application/x-php;type=array => application/json | {"productId": 1} => ["productId": 1]

// conversion from XML to PHP Array
application/xml => application/x-php;type=array | <productId>1</productId> => ["productId": 1]
// conversion from PHP Array to XML
application/x-php;type=array => application/xml | ["productId": 1] => <productId>1</productId>

JMS Convertermake use of Converters registered as Converters in order to provide all the conversion types described in . You can read how to register newConverter in

If you want to customize serialization or deserialization process, you may use of annotations on properties, just like it is describes in .

Register

If you want to make convert nulls for , then you can provide Media Type parameters

JMS Serializer
JMS/Serializer
Annotation section in JMS Serializer
Conversion Table
Module Conversion
Conversion section.
given conversion