diephp/data-object

Simple object to be used as a DTO/MODEL/ValueObject.

v1.0.0 2024-05-24 10:49 UTC

This package is auto-updated.

Last update: 2024-09-24 13:46:13 UTC


README

Simple object to be used as a DTO/MODEL/ValueObject.

Overview

The DataObject class is a versatile data container designed for use as a Data Transfer Object (DTO), Model, or ValueObject. It can be initialized with an associative array and provides various methods for manipulating and accessing data. This class implements both the \JsonSerializable and ArrayAccess interfaces.

Features

  • Initialize with an associative array
  • Implements \JsonSerializable and ArrayAccess interfaces
  • Supports dot notation for nested data access
  • Provides methods for merging, filtering, mapping, and transforming data
  • Automatically converts objects to arrays if they implement a toArray method
  • Various utility methods like hash, flatten, collapse, clone, etc.

Installation

Install the package via Composer:

composer require diephp/dataobject

Or manually add it to your composer.json:

"require": {
    "diephp/dataobject": "^1.0.0"
}

Usage

Initialization

Create a new instance of DataObject:

use DiePHP\DataObject;

$data = new DataObject([
    'name' => 'John Doe',
    'email' => 'john.doe@example.com'
]);

Or use the static of method:

$data = DataObject::of([
    'name' => 'John Doe',
    'email' => 'john.doe@example.com'
]);

Accessing Data

Access data using property notation or array access:

echo $data->name; // John Doe
echo $data['email']; // john.doe@example.com

Check if a key exists:

if ($data->has('name')) {
    // Key exists
}

Manipulating Data

Set a value:

$data->set('name', 'Jane Doe');

Get a value with a default:

$email = $data->get('email', 'default@example.com');

Merge new data:

$data->merge([
    'address' => '123 Main St',
    'phone' => '123-456-7890'
]);

Filter data:

$data->filter(function ($value, $key) {
    return !empty($value);
});

Map data:

$mappedData = $data->map('*', function ($value) {
    return strtoupper($value);
});

Utility Methods

Convert to array:

$array = $data->toArray();

Convert to JSON:

$json = json_encode($data);

Get the MD5 hash of the data:

$hash = $data->hash();

Clone the object:

$clone = $data->clone();

Example

use DiePHP\DataObject;

$data = new DataObject([
    'user' => [
        'name' => 'John Doe',
        'email' => 'john.doe@example.com'
    ]
]);

echo $data->get('user.name'); // John Doe

$data->set('user.address', '123 Main St');
echo $data->get('user.address'); // 123 Main St

$data->merge(['user.phone' => '123-456-7890']);
echo $data->get('user.phone'); // 123-456-7890

$data->filter(function ($value, $key) {
    return !empty($value);
});

echo $data->hash(); // MD5 hash of the data

echo json_encode($data); // JSON representation

License

This project is licensed under the MIT License. See the LICENSE file for details.