ArraySerializableData - viames/pair GitHub Wiki

Pair framework: ArraySerializableData

Pair\Data\ArraySerializableData is a tiny trait for read models whose JSON representation should be the same as toArray().

It implements jsonSerialize() by returning toArray().

Example

use Pair\Data\ArraySerializableData;
use Pair\Data\ReadModel;

/**
 * Public status payload for JSON responses and page state.
 */
final readonly class StatusReadModel implements ReadModel {

	use ArraySerializableData;

	/**
	 * Build the status payload.
	 */
	public function __construct(
		public string $status,
		public int $count
	) {}

	/**
	 * Export the status payload.
	 *
	 * @return	array<string, mixed>
	 */
	public function toArray(): array {

		return [
			'status' => $this->status,
			'count' => $this->count,
		];

	}

}

Then both paths produce the same public shape:

$status = new StatusReadModel('ok', 3);

$status->toArray();
json_encode($status);

When to use

Use the trait when:

  • the read model implements ReadModel
  • toArray() is already the public JSON contract
  • no custom jsonSerialize() behavior is needed

Avoid it when JSON should intentionally differ from the array representation.

See also: ReadModel, MapsFromRecord, JsonResponse.