Skip to content

Commit 7c7f2c7

Browse files
committed
Add documentation to README
1 parent b615a83 commit 7c7f2c7

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

README.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ resolving steps using [code generation](#maximizing-performance).
6060
- [**Creating your own property casters**](#creating-your-own-property-casters)
6161
- [**Static constructors**](#static-constructors)
6262
- [**Key formatters**](#key-formatters)
63+
- [**Serializing maps as objects**](#serializing-maps-as-objects)
6364
- [**Maximizing performance**](#maximizing-performance)
6465

6566
## Design goals
@@ -598,6 +599,59 @@ $payload = $mapper->serializeObject(new Shout('Hello, World!');
598599
$payload['what'] === 'HELLO, WORLD!';
599600
```
600601

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+
601655
## Symmetrical conversion
602656

603657
If configured consistently, hydration and serialization can be used to translate an object to raw data

0 commit comments

Comments
 (0)