maciej-sz/pj-freeze

PHP to JSON Serializer/Deserializer

0.2.1 2016-08-25 10:31 UTC

This package is not auto-updated.

Last update: 2024-12-19 04:13:20 UTC


README

PHP to JSON Serializer/Deserializer

Latest Version on Packagist Build Status No dependencies MIT License

Features

  • Serialization to JSON
  • Unserialization from JSON
  • Circular-reference handling
  • Corresponding JavaScript library is available to read serialized data on the browser side

Usage

This package can be used to serialize and unserialize data objects that contain circular references.

Example: basic round-trip

use MaciejSz\PjFreeze\PjFreeze;

$Freeze = new PjFreeze();

$data = ["foo", "bar", "baz"];

$SerializationResult = $Freeze->serialize($data);
$serializedObj = $SerializationResult->jsonSerialize();

$unserialized = $Freeze->unserialize($serializedObj);
assert($data == $unserialized);

Example: persisting round-trip

An additional step is required for the serialization result to be persisted: PHP's standard json_encode() function has to be called. The json_encode() won't produce "Recursion detected" error this time.

use MaciejSz\PjFreeze\PjFreeze;

$Freeze = new PjFreeze();

$data = ["foo", "bar", "baz"];
$serializedObj = $Freeze->serialize($data)->jsonSerialize();
$serialized_str = json_encode($serializedObj);

file_put_contents("/tmp/data.json", $serialized_str);
// ...
$contents_str = file_get_contents("/tmp/data.json");
$unserialized = $Freeze->unserializeJson($contents_str);
assert($data == $unserialized);

Example: circular reference

Using only json_encode():

// WARNING: this is an example of how NOT to encode circular references
use MaciejSz\PjFreeze\PjFreeze;

$data = new \stdClass();
$data->recursion = $data; // circular reference

$raw_encoded = json_encode($data);
echo json_last_error_msg(); // "Recursion detected"

Using PjFreeze:

use MaciejSz\PjFreeze\PjFreeze;

$data = new \stdClass();
$data->recursion = $data; // circular reference

$Freeze = new PjFreeze();

$serializedObj = $Freeze->serialize($data)->jsonSerialize();
$jp_freeze_encoded = json_encode($serializedObj);
echo json_last_error_msg(); // "No error"

$unserializedObj = json_decode($jp_freeze_encoded);
$unserialized = $Freeze->unserialize($unserializedObj);
assert($unserialized->recursion === $unserialized);

Installation

Via composer:

composer require maciej-sz/pj-freeze