Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Update serializer.rst: deprecate the setCallbacks
Change the deprecated setCallbacks method to the callbacks context option
  • Loading branch information
anvodev authored May 18, 2019
commit 695b706a2e0d644d70552c20b30322f8c4f10239
15 changes: 13 additions & 2 deletions components/serializer.rst
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,12 @@ and ``remove``.
Using Callbacks to Serialize Properties with Object Instances
-------------------------------------------------------------

.. deprecated:: 4.2

The :method:`Symfony\\Component\\Serializer\\Normalizer\\AbstractNormalizer::setCallbacks`
method is deprecated since Symfony 4.2. Use the ``callbacks``
key of the context instead.

When serializing, you can set a callback to format a specific object property::

use App\Model\Person;
Expand All @@ -631,14 +637,19 @@ When serializing, you can set a callback to format a specific object property::
use Symfony\Component\Serializer\Serializer;

$encoder = new JsonEncoder();
$normalizer = new GetSetMethodNormalizer();

// all callback parameters are optional (you can omit the ones you don't use)
$callback = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) {
return $innerObject instanceof \DateTime ? $innerObject->format(\DateTime::ISO8601) : '';
};

$normalizer->setCallbacks(['createdAt' => $callback]);
$defaultContext = [
AbstractNormalizer::CALLBACKS => [
'createdAt' => $callback,
],
];

$normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext);

$serializer = new Serializer([$normalizer], [$encoder]);

Expand Down