-
Notifications
You must be signed in to change notification settings - Fork 0
Serialisation
Want to convert an XML or JSON file to an object? Symfony has built-in features for that. The required classes are in the Serializer namespace.
// These are commonly used classes used for serialisation, import the ones that you need.
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;The Serializer class is used for these file to object conversions and vice versa, let's make a new Serializer object and give it some unconfigured encoder and normalizer objects. This will work just fine in most situations.
$encoders = [new XmlEncoder(), new JsonEncoder()];
$normalizers = [new ObjectNormalizer()];
$serializer = new Serializer($normalizers, $encoders);Let's deserialise XML into an object.
// In this example we simulate an XML file within our code
$data = <<<EOF
<element>
<name>Oxygen</name>
<number>8</number>
<ismetal>false</ismetal>
<stpstate>gas</stpstate>
</element>
EOF;
// This here returns an object of type Element
$element = $serializer->deserialize($data, Element::class, 'xml');You can use any class for deserialisation, The above code would definitely work if Element was an entity. Just remember to import your classes.
Now, you probably want the user to upload an XML file instead of hardcoding it in your code. This can be achieved with a combination of what we learned in Forms and the Serializer.
// You could for example make a form like this with a FileType field
$form = $this->createFormBuilder()
->add('file', FileType::class)
->add('save', SubmitType::class, ['label' => 'Upload'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = file_get_contents(
$form->getData()['file']->getRealPath()
);
$element = $serializer->deserialize($data, Element::class, 'xml');
// We just dump the element to demonstrate that it works.
dd($element);
}To convert an object to XML or JSON, call the serialize() method on you Serializer and pass the object and data format in the arguments.
$pony = new Pony();
$pony->setName('Rainbow Dash');
$pony->setSpecies('Pegasus');
$jsonContent = $serializer->serialize($pony, 'json');Kerntaak 2 & 3
Symfony
= About code maintained by Symfony and not a third party
-
Home
-
Project Setup
-
Users
-
Unit testing
-
PDF
-
File upload
-
Text editing
-
Miscellaneous
-
Laravel
Work in progress.
ASP.NET MVC
= About code maintained or officially supported by Microsoft
-
Project Setup
-
ASP.NET Core MVC setup
- Model
- Controller
- View
-
- Unit Testing
- Inversion of control
ASP.NET Razor Pages
= About code maintained or officially supported by Microsoft
-
Project Setup
- TBA