@@ -589,6 +589,50 @@ Using it in practice::
589
589
// $employeeDto->manager->name === 'Alice'
590
590
// $employeeDto->manager->manager === $employeeDto
591
591
592
+ Decorating the ObjectMapper
593
+ ---------------------------
594
+
595
+ The ``object_mapper `` service can be decorated to add custom logic and state
596
+ management around the mapping process.
597
+
598
+ One can use the
599
+ :class: `Symfony\\ Component\\ ObjectMapper\\ ObjectMapperAwareInterface `. When a
600
+ decorator is applied, it can pass itself to the decorated service (if it implements
601
+ this interface). This allows the underlying services, like the ``ObjectMapper ``,
602
+ to use the top-level decorator's ``map() `` method for recursive mapping, ensuring
603
+ that the decorator's state is consistently used.
604
+
605
+ Here is an example of a decorator that preserves object identity across calls.
606
+ It uses the ``AsDecorator `` attribute to automatically configure itself as a
607
+ decorator for the ``object_mapper `` service:
608
+
609
+ .. code-block :: php
610
+
611
+ // src/ObjectMapper/StatefulObjectMapper.php
612
+ namespace App\ObjectMapper;
613
+
614
+ use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
615
+ use Symfony\Component\ObjectMapper\ObjectMapperAwareInterface;
616
+ use Symfony\Component\ObjectMapper\ObjectMapperInterface;
617
+
618
+ #[AsDecorator(decorates: ObjectMapperInterface::class)]
619
+ final class StatefulObjectMapper implements ObjectMapperInterface
620
+ {
621
+ public function __construct(private ObjectMapperInterface $decorated)
622
+ {
623
+ // Pass this decorator to the decorated service if it's aware
624
+ if ($this->decorated instanceof ObjectMapperAwareInterface) {
625
+ $this->decorated = $this->decorated->withObjectMapper($this);
626
+ }
627
+ }
628
+
629
+ public function map(object $source, object|string|null $target = null): object
630
+ {
631
+ return $this->decorated->map($source, $target);
632
+ }
633
+ }
634
+
635
+
592
636
.. _objectmapper-custom-mapping-logic :
593
637
594
638
Custom Mapping Logic
0 commit comments