@@ -60,6 +60,7 @@ resolving steps using [code generation](#maximizing-performance).
60
60
- [ ** Creating your own property casters** ] ( #creating-your-own-property-casters )
61
61
- [ ** Static constructors** ] ( #static-constructors )
62
62
- [ ** Key formatters** ] ( #key-formatters )
63
+ - [ ** Serializing maps as objects** ] ( #serializing-maps-as-objects )
63
64
- [ ** Maximizing performance** ] ( #maximizing-performance )
64
65
65
66
## Design goals
@@ -598,6 +599,59 @@ $payload = $mapper->serializeObject(new Shout('Hello, World!');
598
599
$payload['what'] === 'HELLO, WORLD!';
599
600
```
600
601
602
+ ### Serializing maps as objects
603
+ By default, associative arrays are serialized as arrays in the payload. Since associative arrays represent
604
+ unstructured key-value maps that are typically treated as objects in many data formats, you may want to serialize
605
+ them as objects for better cross-platform compatibility.
606
+
607
+ You can configure the mapper to serialize associative arrays as objects by enabling the ` serializeMapsAsObjects ` option:
608
+
609
+ ``` php
610
+ use EventSauce\ObjectHydrator\DefinitionProvider;
611
+ use EventSauce\ObjectHydrator\ObjectMapperUsingReflection;
612
+
613
+ $mapper = new ObjectMapperUsingReflection(
614
+ new DefinitionProvider(serializeMapsAsObjects: true),
615
+ );
616
+ ```
617
+
618
+ Maps are serialized as objects based on their doc-comment type hints. Arrays with ` array<string, T> ` type hints
619
+ are treated as maps and serialized as objects.
620
+
621
+ ``` php
622
+ class ExampleCommand
623
+ {
624
+ /**
625
+ * @param array<string , mixed > $changedFields
626
+ */
627
+ public function __construct(
628
+ public readonly array $changedFields,
629
+ ) {}
630
+
631
+ /**
632
+ * @return array<string , string >
633
+ */
634
+ public function metadata(): array
635
+ {
636
+ return [
637
+ 'source' => 'api',
638
+ ];
639
+ }
640
+ }
641
+
642
+ $command = new ExampleCommand(['email' => '
[email protected] ', 'name' => 'John']);
643
+
644
+ $payload = $mapper->serializeObject($command);
645
+ ```
646
+
647
+ Serialized payload:
648
+ ```
649
+ [
650
+ 'changed_fields' => {"email": "[email protected] ", "name": "John"},
651
+ 'metadata' => {"source": "api"}
652
+ ]
653
+ ```
654
+
601
655
## Symmetrical conversion
602
656
603
657
If configured consistently, hydration and serialization can be used to translate an object to raw data
0 commit comments