Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert single entity to an array

Tags:

symfony

What is the most efficient way to convert my Symfony2 entity to an array ? Entity contains protected fields with setters/getters. Is it possible to do with JMSSerializer ?

like image 912
hsz Avatar asked Jan 20 '14 09:01

hsz


3 Answers

Using this bundle is the most efficient way to convert Entities to serialized format. Moreover, it's recommended by Sensio Labs.

To serialize You need only to install, configure this bundle and then:

$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$serializer->serialize($object, 'json');

And deserialize:

$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$object = $serializer->deserialize($jsonData, 'MyNamespace\MyObject', 'json');

Nothing more.

You can also use it to convert an object to an array:

$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$array = $serializer->toArray($object);

Also, you can prevent infinite recursion using serialization groups:

$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$context = \JMS\Serializer\SerializationContext::create();
$context->setGroups($groups);
$serializer->serialize($object, 'json', $context);

Regards

like image 136
Piotr Pasich Avatar answered Sep 27 '22 20:09

Piotr Pasich


Using JMSSerializer for such a simple task seems like an overkill to me. I would use Symfony Serializer Component. The demo page shows how to serialize an entity to JSON.

If you just want to put it to array, you don't need serialization at all, you could just instantiate GetSetMethodNormalizer and use it since component uses arrays as normalized format.

like image 24
Igor Pantović Avatar answered Sep 27 '22 18:09

Igor Pantović


If you have not installed Symfony Serializer Component.

install it composer require symfony/serializer

then just convert any entity to array as follows.

 $serializer = new Serializer(array(new ObjectNormalizer()));
 $data = $serializer->normalize($result, null, array('attributes' => 
   array('success','type','result','errorMessage')));

and the output will be,

$data = array:[ "success" => true "errorMessage" => null "result" => "1" "type" => "url" ]
like image 29
Akoh Victor Gutz Avatar answered Sep 27 '22 19:09

Akoh Victor Gutz