Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[docs] Add documentation to deserialize on existing objects #1308

Merged
merged 1 commit into from
Mar 27, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions doc/cookbook/object_constructor.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
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

.. code-block:: php

<?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);
}
}


2. Register ExistingObjectConstructor.

You should pass ExistingObjectConstructor to DeserializationGraphNavigatorFactory constructor.


3. Add special attribute to DeserializationContext

.. code-block:: php

$context = DeserializationContext::create();
$context->setAttribute('deserialization-constructor-target', $document);
$serializer->deserialize($data, get_class($document), 'json');