suin/marshaller

Type-safe data mapping between JSON and a PHP class object.

1.0.1 2018-01-03 16:00 UTC

This package is auto-updated.

Last update: 2024-04-06 07:52:28 UTC


README

travis-ci-badge packagist-dt-badge license-badge release-version-badge php-version-badge

Type-safe data mapping between JSON and a PHP class object.

Features

  1. Transforms JSON to PHP class object.
  2. Transforms PHP object to JSON.

How does it works?

Marshaller analyze all private properties and convert them into JSON. Unmarshaller analyze the signature of the constructor of the given class and convert JSON into an object.

Installation via Composer

$ composer require suin/marshaller

Usage

Marshal object and Unmarshal JSON

This is the simplest use case of Marshaller.

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"
// }

Please see example#01 for details.

Protocols

Sometimes you would want to decode a JSON value in special transform way. In such a case, you can also define transforming rules between a PHP object and a JSON object by using Protocols and Formats.

A Format describes how a single class or type becomes JSON and vice versa. All Formats must follow the interface below:

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

For example, a Format is implemented like this:

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';
    }
}

Also, a protocol is a class that have a collection of Formats. The following example has only one format, but some more formats would be included here in real use case.

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

To see complete example code of protocols and formats, please see example#02. Also a complex example is seen in ./tests/ExampleModel/StudentProtocol.php

Changelog

Please see CHANGELOG for more details.

Contributing

Please see CONTRIBUTING for more details.