Skip to content

Commit d611e77

Browse files
committed
feature symfony#3701 [Serializer] add documentation for serializer callbacks (cordoval)
This PR was submitted for the master branch but it was merged into the 2.3 branch instead (closes symfony#3701). Discussion ---------- [Serializer] add documentation for serializer callbacks related symfony/symfony#10229 | Q | A | | --- | --- | | Doc fix? | no | | New docs? | yes | | Applies to | 2.3+ | | Fixed tickets | self 👶 | | License | CC-ASA 3.0 Unported | Sent using [Gush](https://github.com/gushphp/gush) Commits ------- b865b40 add comma madness and lowercasing W efe2029 plug new revision eabdbd0 add serializer set callback documentation
2 parents 80c645c + a06ad9a commit d611e77

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

components/serializer.rst

+31
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,37 @@ method on the normalizer definition::
181181
As a final result, the deserializer uses the ``first_name`` attribute as if
182182
it were ``firstName`` and uses the ``getFirstName`` and ``setFirstName`` methods.
183183

184+
Using Callbacks to Serialize Properties with Object Instances
185+
-------------------------------------------------------------
186+
187+
When serializing, you can set a callback to format a specific object property::
188+
189+
use Acme\Person;
190+
use Symfony\Component\Serializer\Encoder\JsonEncoder;
191+
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
192+
use Symfony\Component\Serializer\Serializer;
193+
194+
$encoder = new JsonEncoder();
195+
$normalizer = new GetSetMethodNormalizer();
196+
197+
$callback = function ($dateTime) {
198+
return $dateTime instanceof \DateTime
199+
? $dateTime->format(\DateTime::ISO8601)
200+
: '';
201+
}
202+
203+
$normalizer->setCallbacks(array('createdAt' => $callback));
204+
205+
$serializer = new Serializer(array($normalizer), array($encoder));
206+
207+
$person = new Person();
208+
$person->setName('cordoval');
209+
$person->setAge(34);
210+
$person->setCreatedAt(new \DateTime('now'));
211+
212+
$serializer->serialize($person, 'json');
213+
// Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"}
214+
184215
JMSSerializer
185216
-------------
186217

0 commit comments

Comments
 (0)