Skip to content

Instantly share code, notes, and snippets.

@afurculita
Forked from baldurrensch/CustomHandler.php
Last active August 29, 2015 14:18
Show Gist options
  • Save afurculita/b26494b938cc6bf9b167 to your computer and use it in GitHub Desktop.
Save afurculita/b26494b938cc6bf9b167 to your computer and use it in GitHub Desktop.
This is a handler for the JMS serializer to handle parent and child type serialization. You need to set the type of your collection as `@Type("\Acme\MyBundle\Model\ChildType")`, so that the serializer picks up the handler correctly. Also remember that you need to hook up the handler as a service (and give it the correct tag).
<?php
namespace Acme\MyBundle\Serializer\Handler;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\EventDispatcher\Event;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\XmlSerializationVisitor;
use JMS\Serializer\GenericSerializationVisitor;
use Acme\MyBundle\Model\MyCustomParentType;
/**
* Custom Handler for Parent and Child Types
*/
class CustomHandler implements SubscribingHandlerInterface
{
public static function getSubscribingMethods()
{
$methods = array();
foreach (array('json', 'xml', 'yml') as $format) {
$methods[] = array(
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => $format,
'type' => 'Acme\MyBundle\Model\MyCustomParentType',
'method' => 'serializeTo'.('xml' == $format ? 'XML' : 'Array'),
);
}
return $methods;
}
public function serializeToXML(XmlSerializationVisitor $visitor, MyCustomParentType $object, array $type)
{
if ($object instanceof \Acme\MyBundle\Model\ChildType1) {
return $visitor->getNavigator()->accept($object, null, $visitor);
} else if (...) {
...
}
}
public function serializeToArray(GenericSerializationVisitor $visitor, MyCustomParentType $object, array $type)
{
...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment