The default Serializer service is created during dependency injection phase, and the Serializer interface do not allow editing of (full) retrieval of normalizers.
I think you have (at least) three choice here:
- add your custom normalizer to the default Serializer service
- add NormalizableInterface to your entities
- create a new Serializer service (or a local object as suggested by the docs) as you were trying to do.
I think in your scenario, case 1 is preferred (since 2 becomes boring pretty fast).
I would do something like this; first create a custom Normalizer
<?php
namespace AppBundle;
class DateTimeNormalizer extends SerializerAwareNormalizer implements NormalizerInterface, DenormalizerInterface
{
/**
* {@inheritdoc}
*/
public function normalize($object, $format = null, array $context = array())
{
return $object->format(DateTime::ISO8601);
}
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = null, array $context = array())
{
return new $class($data);
}
/**
* Checks if the given class is a DateTime.
*
* @param mixed $data Data to normalize.
* @param string $format The format being (de-)serialized from or into.
*
* @return bool
*/
public function supportsNormalization($data, $format = null)
{
return $data instanceof DateTime;
}
/**
* Checks if the given class is a DateTime.
*
* @param mixed $data Data to denormalize from.
* @param string $type The class to which the data should be denormalized.
* @param string $format The format being deserialized from.
*
* @return bool
*/
public function supportsDenormalization($data, $type, $format = null)
{
$class = new ReflectionClass($type);
return $class->isSubclassOf('DateTime');
}
}
Then register it to your services:
# app/config/services.yml
services:
datetime_normalizer:
class: AppBundleDateTimeNormalizer
tags:
- { name: serializer.normalizer }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…