Skip to content

Update serializer.rst: deprecate the setCallbacks #11584

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

Merged
merged 1 commit into from
May 24, 2019
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
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