Hello all!
Today one tip (for a tip!), for automatic, correct, recursive, pain-free method to converting php object to json, under symfony 5 php framework.
You know it's a common need but not so well addressed in fact, with such a simplicity, avoiding programming an exact 1:1 manual mapping or programming it's own function to do that.
It my case, i get mongo odm results from a doctrine repository findall(), and get an array of objects (templates here).
I wanted an easy, recursive (automatique) object conversion to php associative array, to make use of it.
Let me show you a convenient way to do this:
We'll use symfony's serializer module's components (serializer is part of the base deployment with composer, so no need in installing anything).
In object class:
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
class Template { ...
// iders
// getters
// setters
// issers
// whatever
// and a special function for json conversion, note it's a public function
public static function converttoarray($templates) {
$encoders = [newXmlEncoder(), newJsonEncoder()];
$normalizers = [newObjectNormalizer()];
$serializer = newSerializer($normalizers, $encoders);
$i = 0;
foreach($templates as $template) {
$templates[$i] = json_decode($serializer->serialize($template, 'json'), true);
$i++;
}
return$templates;
}
}
To be called in a controller:
$result['templates'] = $dm->getRepository(Template::class)->findAll();
$result['templates'] = Template::converttoarray($result['templates']);
Ok, that's done! Enjoy!
Feel free to tip me, it will encourage me to publish more interesting and useful content!
Have you read my other posts, click here!
Follow me on publish0x, and on twitter!
See you all!