PHP code example of aternos / serializer

1. Go to this page and download the library: Download aternos/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/ */

    

aternos / serializer example snippets


use Aternos\Serializer\Serialize;
use Aternos\Serializer\Json\PropertyJsonSerializer;

class ExampleClass implements \JsonSerializable {
    use PropertyJsonSerializer;

    public function __construct(
        #[Serialize]
        protected string $name,
        #[Serialize(ception $e) {
    // handle exception
}

$example = ExampleClass::fromJson('{ "name": "John", "age": 25, "last_name": "Doe" }');
// ^ throws an exception if the input is invalid (e.g. 

$example = new ExampleClass("John", 25, "Doe");
$serializer = new \Aternos\Serializer\Json\JsonSerializer();
try {
    $json = $serializer->serialize($example);
} catch (MissingPropertyException|IncorrectTypeException $e) {
    // handle exception
}

$deserializer = new \Aternos\Serializer\Json\JsonDeserializer(ExampleClass::class);
try {
    $example = $deserializer->deserialize($json);
} catch (SerializationException|JsonException $e) {
    // handle exception
}

#[Serialize(name: "last_name")]
protected ?string $lastName = null;

#[Serialize(name: "0")]
protected string $zero = "Example";

#[Serialize]
protected string $name;
// ^ ^ not lt value (1) is used

#[Serialize(e)]
protected string $notRequired;
// ^ not fatal PHP error

#[Serialize]
protected string $a;
// ^ does not allow null

#[Serialize(allowNull: false)]
protected ?string $c = null;
// ^ does not allow null

#[Serialize]
protected ?string $b;
// ^ allows null

#[Serialize(allowNull: true)]
protected string $c;
// ^ allows null
// If not set in the serialized data, the property is not initialized
// Accessing it before initialization will result in a fatal PHP error

#[Serialize(itemType: ExampleClass::class)]
protected array $examples;
// ^ items in the array will be converted to ExampleClass

#[Serialize]
protected array $otherExamples;
// ^ items in the array will not be converted

#[Serialize(serializer: new Base64Serializer(), deserializer: new Base64Deserializer(TestClass::class))]
protected TestClass $example;

#[Serialize(itemSerializer: new Base64Serializer(), itemDeserializer: new Base64Deserializer(TestClass::class))]
protected array $example = [];

$example = new ExampleClass("John", 25, "Doe");
$serializer = new \Aternos\Serializer\Array\ArraySerializer();
$deserializer = new \Aternos\Serializer\Array\ArrayDeserializer(ExampleClass::class);
try {
    $array = $serializer->serialize($example);
    // ^ ['name' => 'John', 'age' => 25, 'last_name' => 'Doe']
    $example = $deserializer->deserialize($array);
} catch (SerializationException $e) {
    // handle exception
}