Skip to content

Commit 59ef484

Browse files
committed
Merge branch '7.4' into 8.0
* 7.4: Tweaks [ObjectMapper] Add ObjectMapperAwareInterface to set the owning object
2 parents 8e17418 + e130ceb commit 59ef484

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

object_mapper.rst

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -585,6 +585,51 @@ Using it in practice::
585585
// $employeeDto->manager->name === 'Alice'
586586
// $employeeDto->manager->manager === $employeeDto
587587

588+
Decorating the ObjectMapper
589+
---------------------------
590+
591+
The ``object_mapper`` service can be decorated to add custom logic or manage
592+
state around the mapping process.
593+
594+
You can use the :class:`Symfony\\Component\\ObjectMapper\\ObjectMapperAwareInterface`
595+
to enable the decorated service to access the outermost decorator. If the
596+
decorated service implements this interface, the decorator can pass itself to
597+
it. This allows underlying services, like the ``ObjectMapper``, to call the
598+
decorator's ``map()`` method during recursive mapping, ensuring that the
599+
decorator's state is used consistently throughout the process.
600+
601+
Here's an example of a decorator that preserves object identity across calls.
602+
It uses the ``AsDecorator`` attribute to automatically configure itself as a
603+
decorator of the ``object_mapper`` service::
604+
605+
// src/ObjectMapper/StatefulObjectMapper.php
606+
namespace App\ObjectMapper;
607+
608+
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
609+
use Symfony\Component\ObjectMapper\ObjectMapperAwareInterface;
610+
use Symfony\Component\ObjectMapper\ObjectMapperInterface;
611+
612+
#[AsDecorator(decorates: ObjectMapperInterface::class)]
613+
final class StatefulObjectMapper implements ObjectMapperInterface
614+
{
615+
public function __construct(private ObjectMapperInterface $decorated)
616+
{
617+
// pass this decorator to the decorated service if it's aware
618+
if ($this->decorated instanceof ObjectMapperAwareInterface) {
619+
$this->decorated = $this->decorated->withObjectMapper($this);
620+
}
621+
}
622+
623+
public function map(object $source, object|string|null $target = null): object
624+
{
625+
return $this->decorated->map($source, $target);
626+
}
627+
}
628+
629+
.. versionadded:: 7.4
630+
631+
The feature to decorate the ObjetMapper was introduced in Symfony 7.4.
632+
588633
.. _objectmapper-custom-mapping-logic:
589634

590635
Custom Mapping Logic

0 commit comments

Comments
 (0)