PHP code example of suin / marshaller

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

    

suin / marshaller example snippets


use Suin\Marshaller\JsonMarshaller;
use Suin\Marshaller\StandardProtocol;

// Transform an object to JSON.
$marshaller = new JsonMarshaller(new StandardProtocol);
$json = $marshaller->marshal(new Cat('Oliver'));
var_dump($json);
// Output:
// string(17) "{"name":"Oliver"}"

// Transform JSON to an object.
$cat = $marshaller->unmarshal($json, Cat::class);
var_dump($cat);
// Output:
// object(Cat)#%d (1) {
//   ["name":"Cat":private]=>
//   string(6) "Oliver"
// }

interface Format<A, B> {
  public function read(A $jsonValue): B
  public function write(B $object): A
}

class HealthFormat // naming rule: class name + "Format"
{
    // Define how transform a JSON value to a PHP object.
    public function read(string $health): Health
    {
        return new Health($health === 'healthy');
    }

    // Define how transform a PHP object to a JSON value.
    public function write(Health $health): string
    {
        return $health->isHealthy() ? 'healthy' : 'sick';
    }
}

class HealthProtocol extends StandardProtocol
{
    public function __construct()
    {
        parent::__construct(
            new HealthFormat
        );
    }
}