On Github Tom32i / talk-serializer
💰 Valeur métier 💰
public function normalize($object, $format = null, array $context = array()) { return [ 'id' => $object->getId(), 'name' => $object->getName(), 'groups' => array_map( function (Group $group) { return $group->getId(); }, $object->getGroups() ) ]; }
class UserNormalizer implements NormalizerInterface {}
public function supportsNormalization($data, $format = null) { return $data instanceof User; }
[ 'id' => 1, 'name' => 'Foo Bar', 'groups' => [1, 2] ]
public function normalize($object, $format = null, array $context = array()) { return [ // ... 'groups' => array_map( function ($object) use ($format, $context) { return $this->serializer->normalize($object, $format, $context); }, $object->getGroups() ), ]; }
class UserNormalizer extends SerializerAwareNormalizer implements NormalizerInterface {}
class GroupNormalizer extends SerializerAwareNormalizer implements NormalizerInterface { public function normalize($object, $format = null, array $context = array()) { return [ 'id' => $object->getId(), 'name' => $object->getName(), ]; } public function supportsNormalization($data, $format = null) { return $data instanceof Group; } }
[ 'id' => 1, 'firstname' => 'Foo', 'lastname' => 'Bar', 'groups' => [ [ 'id' => 1, 'name' => 'FooFighters' ], [ 'id' => 2, 'name' => 'BarFighters' ], ], ]
services: # Serializer acme.serializer.default: class: 'Symfony\Component\Serializer\Serializer' arguments: 0: - '@acme.normalizer.user' - '@acme.normalizer.group' - '@serializer.normalizer.object' 1: - '@acme.encoder.json' - '@acme.encoder.xml'
services: # JSON Encoder acme.encoder.json: class: 'Symfony\Component\Serializer\Encoder\JsonEncoder' # XML Encoder acme.encoder.xml: class: 'Symfony\Component\Serializer\Encoder\XmlEncoder'
services: # User Normalizer acme.normalizer.user: class: 'Acme\Serializer\Normalizer\UserNormalizer' # Group Normalizer acme.normalizer.group: class: 'Acme\Serializer\Normalizer\GroupNormalizer'