PHP code example of byjg / serializer

1. Go to this page and download the library: Download byjg/serializer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

byjg / serializer example snippets



$result = \ByJG\Serializer\SerializerObject::instance($data)->serialize();
$result2 = \ByJG\Serializer\SerializerObject::instance($anyJsonString)->fromJson()->serialize();
$result3 = \ByJG\Serializer\SerializerObject::instance($anyYamlString)->fromYaml()->serialize();


$data = [ ... any array content ... ]

echo (new JsonFormatter())->process($data);
echo (new XmlFormatter())->process($data);
echo (new YamlFormatter())->process($data);
echo (new PlainTextFormatter())->process($data);


$myclass->setName('Joao');
$myclass->setAge(null);

$serializer = new \ByJG\Serializer\SerializerObject($myclass);
$result = $serializer->serialize();
print_r($result);

// Will return:
// Array
// (
//     [name] => Joao
//     [age] => 
// )


$result = \ByJG\Serializer\SerializerObject::instance($myclass)
            ->withDoNotSerializeNull()
            ->serialize();
print_r($result);

// And the result will be:
// Array
// (
//     [name] => Joao
// )



$result = \ByJG\Serializer\SerializerObject::instance($myclass)
            ->withDoNotParse([
                MyClass::class
            ])
            ->serialize();


// Create the class
class MyClass extends BindableObject
{}

// Bind any data into the properties of myclass
$myclass->bindFrom($data);

// You can convert to array all properties
$myclass->bindTo($otherobject);

// Set all properties from $source that matches with the property in $target
BinderObject::bind($source, $target);

// Convert all properties of any object into array
SerializerObject::serialize($source);

class Source
{
    public $idModel;
    public $clientName;
    public $age;
}

class Target
{
    public $id_model;
    public $client_name;
    public $age;
}

$source = new Source();
$source->idModel = 1;
$source->clientName = 'John';
$source->age = 30;

BinderObject::bind($source, $target, new CamelToSnakeCase());

class Source
{
    public $id_model;
    public $client_name;
    public $age;
}

class Target
{
    public $idModel;
    public $clientName;
    public $age;
}

$source = new Source();
$source->id_model = 1;
$source->client_name = 'John';
$source->age = 30;

BinderObject::bind($source, $target, new SnakeToCamelCase());