Versions

Table Of Contents

Support

You can obtain free community support for example through stackoverflow.

If you think you found a bug, please create a ticket in the bug tracker.


Continuous Inspections

If you take code quality seriously, try out the new continuous inspection service.
scrutinizer-ci.com

GitHub

Object constructor

Deserialize on existing objects

By default, a brand new instance of target class is created during deserialization. To deserialize into an existing object, you need to perform the following steps.

  1. Create new class which implements ObjectConstructorInterface
<?php declare(strict_types=1);

namespace Acme\ObjectConstructor;

use JMS\Serializer\Construction\ObjectConstructorInterface;
use JMS\Serializer\DeserializationContext;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Visitor\DeserializationVisitorInterface;

class ExistingObjectConstructor implements ObjectConstructorInterface
{
    public const ATTRIBUTE = 'deserialization-constructor-target';

    private $fallbackConstructor;

    public function __construct(ObjectConstructorInterface $fallbackConstructor)
    {
        $this->fallbackConstructor = $fallbackConstructor;
    }

    public function construct(DeserializationVisitorInterface $visitor, ClassMetadata $metadata, $data, array $type, DeserializationContext $context): ?object
    {
        if ($context->hasAttribute(self::ATTRIBUTE)) {
            return $context->getAttribute(self::ATTRIBUTE);
        }

        return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
    }
}
  1. Register ExistingObjectConstructor.

You should pass ExistingObjectConstructor to DeserializationGraphNavigatorFactory constructor.

  1. Add special attribute to DeserializationContext
$context = DeserializationContext::create();
$context->setAttribute('deserialization-constructor-target', $document);
$serializer->deserialize($data, get_class($document), 'json');