Permalink
Browse files

feature #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 #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
  • Loading branch information...
weaverryan committed Apr 2, 2014
2 parents 80c645c + a06ad9a commit d611e77fa1408064c6f066c6acd9d8b4464198ef
Showing with 31 additions and 0 deletions.
  1. +31 −0 components/serializer.rst
View
@@ -181,6 +181,37 @@ method on the normalizer definition::
As a final result, the deserializer uses the ``first_name`` attribute as if
it were ``firstName`` and uses the ``getFirstName`` and ``setFirstName`` methods.
Using Callbacks to Serialize Properties with Object Instances
-------------------------------------------------------------
When serializing, you can set a callback to format a specific object property::
use Acme\Person;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Serializer;
$encoder = new JsonEncoder();
$normalizer = new GetSetMethodNormalizer();
$callback = function ($dateTime) {
return $dateTime instanceof \DateTime
? $dateTime->format(\DateTime::ISO8601)
: '';
}
$normalizer->setCallbacks(array('createdAt' => $callback));
$serializer = new Serializer(array($normalizer), array($encoder));
$person = new Person();
$person->setName('cordoval');
$person->setAge(34);
$person->setCreatedAt(new \DateTime('now'));
$serializer->serialize($person, 'json');
// Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"}
JMSSerializer
-------------

0 comments on commit d611e77

Please sign in to comment.