Reputation: 8548
I am trying to work out a good way of storing an array of objects in my sym2 entity. The objects in the array would look like this:
{
"id" : 1,
"top" : 200,
"left" : 150,
"width" : 500,
"height" : 600
}
Should I just go for the array property like this?
/**
* @var array $modules
*
* @ORM\Column(name="modules", type="array", nullable=true)
*/
private $modules;
/*
{
"id" : 1,
"left" : 150,
"top" : 200,
"width" : 500,
"height" : 600
}
*/
Or is there a smoother way, could I create the objects contained in this array as a separate entity and store instead an array of those entities here in this entity?
I do not want to save these to database separately, I would like to keep them inside this main entity. I get that I could set up a many to many relationship but I don't want to, it is a bit overkill for what I am trying to accomplish.
----- UPDATE ------- Thanks to Guillaume Verbal, here's what I will do, I assume this will work fine as well then since JSON can take nested objects infinitely?
$person[0] = new Acme\Person();
$person->setName('foo');
$person->setAge(99);
$person[1] = new Acme\Person();
$person->setName('foo');
$person->setAge(99);
$jsonContent = $serializer->serialize($person, 'json');
// $jsonContent contains {"name":"foo","age":99}
Upvotes: 0
Views: 5544
Reputation: 503
You can use the Symfony 2 Serializer Component: http://symfony.com/doc/current/components/serializer.html
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$person = new Acme\Person();
$person->setName('foo');
$person->setAge(99);
$jsonContent = $serializer->serialize($person, 'json');
// $jsonContent contains {"name":"foo","age":99}
Upvotes: 4
Reputation: 3698
You can use JSON type for this
http://symfony.com/doc/current/components/serializer.html
Upvotes: 1