Skip to content

Commit 084c4e6

Browse files
committed
minor #21225 [ObjectMapper] Add ObjectMapperAwareInterface to set the owning object (soyuka)
This PR was merged into the 7.4 branch. Discussion ---------- [ObjectMapper] Add ObjectMapperAwareInterface to set the owning object #21224 Commits ------- 97af218 [ObjectMapper] Add ObjectMapperAwareInterface to set the owning object
2 parents e0c2c21 + 97af218 commit 084c4e6

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

object_mapper.rst

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,48 @@ Using it in practice::
589589
// $employeeDto->manager->name === 'Alice'
590590
// $employeeDto->manager->manager === $employeeDto
591591

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+
// src/ObjectMapper/StatefulObjectMapper.php
610+
namespace App\ObjectMapper;
611+
612+
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
613+
use Symfony\Component\ObjectMapper\ObjectMapperAwareInterface;
614+
use Symfony\Component\ObjectMapper\ObjectMapperInterface;
615+
616+
#[AsDecorator(decorates: ObjectMapperInterface::class)]
617+
final class StatefulObjectMapper implements ObjectMapperInterface
618+
{
619+
public function __construct(private ObjectMapperInterface $decorated)
620+
{
621+
// Pass this decorator to the decorated service if it's aware
622+
if ($this->decorated instanceof ObjectMapperAwareInterface) {
623+
$this->decorated = $this->decorated->withObjectMapper($this);
624+
}
625+
}
626+
627+
public function map(object $source, object|string|null $target = null): object
628+
{
629+
return $this->decorated->map($source, $target);
630+
}
631+
}
632+
633+
592634
.. _objectmapper-custom-mapping-logic:
593635

594636
Custom Mapping Logic

0 commit comments

Comments
 (0)