Serialize any object into array and format it JSON or XML
Just use the Serializer class with any kind of object, stdClass or array;
<?php
$serializer = new \ByJG\Serializer\SerializerObject($data);
$result = $object->build();
$result
is an array. You can use a Formatter to transform it in JSON or XML.
<?php
$serializer = new \ByJG\Serializer\SerializerObject($data);
$result = $serializer->build();
echo (new JsonFormatter())->process($result);
echo (new XmlFormatter())->process($result);
setBuildNull(false)
The SerializerObject brings all properties by default. For example:
<?php
$myclass->setName('Joao');
$myclass->setAge(null);
$serializer = new \ByJG\Serializer\SerializerObject($myclass);
$result = $serializer->build();
print_r($result);
// Will return:
// Array
// (
// [name] => Joao
// [age] =>
// )
But you can setup for ignore the null elements:
<?php
$serializer = new \ByJG\Serializer\SerializerObject($myclass);
$result = $serializer->setBuildNull(false)->build();
print_r($result);
// And the result will be:
// Array
// (
// [name] => Joao
// )
setDoNotParse([object])
Sometimes we want to serialize the object but ignore some class types.
Setting this option below the whole classes defined in the setDoNotParse will be ignored and not parsed:
<?php
$serializer = new \ByJG\Serializer\SerializerObject($myclass);
$result = $serializer->setDoNotParse([
MyClass::class
]);
Add to the object the method bind
that allows set contents from another object
<?php
// Create the class
class MyClass extends BinderObject
{}
// Bind any data into the properties of myclass
$myclass->bind($data);
// You can convert to array all properties
$myclass->toArray();
// Set all properties from $source that matches with the property in $target
BinderObject::bindObject($source, $target);
// Convert all properties of any object into array
BinderObject::toArrayFrom($source);
composer require "byjg/serialize=1.0.*"
phpunit