Skip to content

Commit dce3cc2

Browse files
cordovalweaverryan
authored andcommitted
add serializer set callback documentation
1 parent 80c645c commit dce3cc2

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

components/serializer.rst

+27
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,33 @@ 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 DateTime Objects
185+
---------------------------------------------
186+
187+
If you have DateTime type fields or need special formatting needs when deserializing
188+
a particular property from your object you can use the callbacks feature::
189+
190+
$encoder = new JsonEncoder();
191+
$normalizer = new GetSetMethodNormalizer();
192+
193+
$callback = function ($dateTime) {
194+
return $dateTime instanceof \DateTime
195+
? $dateTime->format(\DateTime::ISO8601)
196+
: '';
197+
}
198+
199+
$normalizer->setCallbacks(array('createdAt' => $callback));
200+
201+
$serializer = new Serializer(array($normalizer), array($encoder));
202+
203+
$person = new Acme\Person();
204+
$person->setName('cordoval');
205+
$person->setAge(34);
206+
$person->setCreatedAt(new \DateTime('now'));
207+
208+
$serializer->serialize($person, 'json');
209+
// Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"}
210+
184211
JMSSerializer
185212
-------------
186213

0 commit comments

Comments
 (0)