Map arrays into Data Transfer Objects

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/mementohub/data

dev-main 2025-11-28 07:36 UTC

This package is auto-updated.

Last update: 2025-12-28 07:55:23 UTC


README

A lightweight package that enables casting multidimensional arrays to objects and vice versa.

Installation

You can install the package via composer:

composer require mementohub/data

Usage

Defining a Data Class

To define a data class, create a class that extends Mementohub\Data\Data and add properties to it.

<?php

namespace App\Data;

use Mementohub\Data\Data;

class User extends Data
{
    public function __construct(
        public readonly string $name,
        public readonly string $email,
        public readonly DateTimeImmutable $birthday,
        /** @var Team[] */
        public readonly array $teams
    ) {}
}

class Team extends Data
{
    public function __construct(
        public readonly string $name,
        public readonly string $description,
    ) {}
}

Parsing into Data

To parse an array into a data class, use the from method.

$user = User::from([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'birthday' => '2023-01-01',
    'teams' => [
        [
            'name' => 'Team 1',
            'description' => 'Description 1',
        ],
        [
            'name' => 'Team 2',
            'description' => 'Description 2',
        ],
    ],
]);

Transforming to Array

To transform a data class to an array, use the toArray method.

$array = $user->toArray();

Inspiration