PHPackages                             rkt/magento-data - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. rkt/magento-data

ActiveMagento2-module[Utility &amp; Helpers](/categories/utility)

rkt/magento-data
================

Data Object &amp; Data Transfer Objects for Magento 2

1.0.1(8mo ago)2218↑100%12BSD-3-ClausePHP

Since Aug 11Pushed 8mo ago1 watchersCompare

[ Source](https://github.com/rajeev-k-tomy/magento-data)[ Packagist](https://packagist.org/packages/rkt/magento-data)[ RSS](/packages/rkt-magento-data/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (2)Versions (4)Used By (2)

Rkt\_MageData
=============

[](#rkt_magedata)

A powerful, lightweight **Data Object &amp; DTO (Data Transfer Object)** system for **Magento 2** — supporting smart instantiation, validation, and serialization.

---

🚀 Installation
--------------

[](#-installation)

```
composer require rkt/magento-data
```

---

✨ Features Overview
-------------------

[](#-features-overview)

### 1. ✅ Easy Data Object Instantiation

[](#1--easy-data-object-instantiation)

Use the static `from()` or `create()` methods to easily instantiate data objects.

#### Example

[](#example)

```
use Rkt\MageData\Data;

class ProductImageData extends Data
{
    public function __construct(
        public string $src,
        public ?string $alt = null,
    ) {}
}
```

You can instantiate it like this:

```
$image = ProductImageData::from([
    'src' => 'https://example.com/image.jpg',
    'alt' => 'Awesome image'
]);
```

Or using `create()`:

```
$image = ProductImageData::create([
    'src' => 'https://example.com/image.jpg',
    'alt' => 'Awesome image'
]);
```

---

### 2. 🛡 Validation Built In

[](#2--validation-built-in)

This module includes built-in validation using [`rakit/validation`](https://github.com/rakit/validation).

#### 🔹 Basic Validation

[](#-basic-validation)

Just define a `rules()` method in your data object:

```
class Customer extends Data
{
    public function __construct(
        public string $email,
        public string $firstname,
        public string $lastname,
        public array $street,
    ) {}

    public function rules(): array
    {
        return [
            'email' => 'email|required',
            'firstname' => 'required|min:1|max:250',
            'lastname' => 'required|min:1|max:250',
            'street.0' => 'required',
        ];
    }
}
```

> You can validate array elements (like `street.0`) using dot notation.

#### 🔹 Custom Validation Messages

[](#-custom-validation-messages)

Override `messages()`:

```
public function messages(): array
{
    return [
        'email:email' => __('Customer email is invalid.'),
        'firstname:required' => __('First name cannot be empty.'),
    ];
}
```

#### 🔹 Custom Field Aliases

[](#-custom-field-aliases)

Override `aliases()`:

```
public function aliases(): array
{
    return [
        'email' => __('Email Address'),
    ];
}
```

In error messages, `email` will now appear as "Email Address".

---

### 3. 🧩 Nested Object Validation

[](#3--nested-object-validation)

Nested and recursive validation works out of the box:

```
class Person extends Data
{
    public function __construct(public string $firstname) {}

    public function rules(): array
    {
        return ['firstname' => 'required'];
    }
}

class Family extends Data
{
    public function __construct(
        public Person $father,
        public Person $mother,
        public ?array $children = [],
    ) {}

    public function rules(): array
    {
        return [
            'father' => 'required',
            'mother' => 'required',
        ];
    }
}
```

✅ In this setup:

- `father` and `mother` are required and must pass `Person` validation.
- `children` can be a list of `Person`, and they’ll be validated too (if provided).

---

### 4. 🔹 Custom Validation Rules via `customRules()`

[](#4--custom-validation-rules-via-customrules)

You can define reusable or inline validation rules using `customRules()`. Two types of custom rules are supported:

#### ✅ 1. **Closure-Based Rules**

[](#-1-closure-based-rules)

Use closures for simple, inline validation logic.

```
public function rules(): array
{
    return [
        'email' => 'required|company_email',
    ];
}

public function customRules(): array
{
    return [
        'company_email' => function ($value) {
            return str_ends_with($value, '@example.com');
        },
    ];
}
```

> ℹ️ The closure is automatically registered using the [`callback` rule](https://github.com/rakit/validation#callback-rule) provided by `rakit/validation`.

---

#### ✅ 2. **Custom Rule Class**

[](#-2-custom-rule-class)

For more reusable or complex logic, use a rule class. The given rule must be in compliance with [rakit/validation](https://github.com/rakit/validation?tab=readme-ov-file#registeroverride-rule). Basically the rule class must extend `Rakit\Validation\Rule`.

```
use Rakit\Validation\Rule;

class CompanyEmailRule extends Rule
{
    protected $message = ':attribute must be a company email (e.g. @example.com).';

    public function check($value): bool
    {
        return str_ends_with($value, '@example.com');
    }
}
```

```
public function rules(): array
{
    return [
        'email' => 'required|company_email',
    ];
}

public function customRules(): array
{
    return [
        'company_email' => CompanyEmailRule::class,
    ];
}
```

> ✅ You can also return an instantiated object if needed — it will be registered directly.

---

### 5. 🧵 Event-Driven Rule Customization

[](#5--event-driven-rule-customization)

You can dynamically modify validation rules/messages/aliases using Magento events.

#### 🔹 Example

[](#-example)

```
namespace Rkt\Example\Data;

class MyData extends Data
{
    public function __construct(public string $email) {}

    public function rules(): array
    {
        return ['email' => 'required'];
    }
}
```

#### 🔸 Event Name

[](#-event-name)

When `validate()` is called, the event `rkt_example_data_mydata_validate_before` is dispatched.

#### 🔹 Observer Configuration (`events.xml`)

[](#-observer-configuration-eventsxml)

```

```

#### 🔹 Sample Observer

[](#-sample-observer)

```
class UpdateMyDataValidation implements ObserverInterface
{
    public function execute(Observer $observer)
    {
        $transport = $observer->getData('transport');

        $rules = $transport->getData('rules');
        $rules['email'] = 'required|email';

        $aliases = $transport->getData('aliases');
        $aliases['email'] = 'Email Address';

        $transport->setData('rules', $rules);
        $transport->setData('aliases', $aliases);
    }
}
```

✅ Now your validation dynamically adds the `email` rule and alias based on observer logic.

---

### 6. 🔄 Serialization Support

[](#6--serialization-support)

Convert data objects to array or JSON easily:

```
$data->toArray(); // → returns an array representation

$data->toJson(); // → returns a JSON string
```

### 7. Fetch validations rules applicable to the data

[](#7-fetch-validations-rules-applicable-to-the-data)

You can get the validation rules applicable for a payload like this.

```
class Family extends Data
{
    public function __construct(
        public Person $father,
        public Person $mother,
        public ?array $children = [],
    ) {
    }

    public function rules(): array
    {
        return [
            'father' => 'required',
            'mother' => 'required',
            'children' => 'array|nullable'
        ];
    }
}

class Person extends Data
{
    use UseValidation;

    public function __construct(
        public string $firstname,
        public string $lastname,
        public string $email,
    ) {
    }

    public function rules(): array
    {
        return [
            'email' => 'required|email',
            'firstname' => 'required',
            'lastname' => 'required',
        ];
    }
}
```

Now if you call

```
$rules = Family::getValidationRules([
    'father' => ['firstname' => 'John', 'lastname' => 'Doe', 'email' => 'john@example.com'],
    'mother' => ['firstname' => 'Jane', 'lastname' => 'Doe', 'email' => 'jane@example.com'],
    'children' => [
        ['firstname' => 'Jimmy', 'lastname' => 'Doe', 'email' => 'jimmy@example.com'],
    ],
]);
```

Will provide you below result:

```
$rules = [
    'father' => 'required',
    'father.firstname' => 'required',
    'father.lastname' => 'required',
    'father.email' => 'required|email',
    'mother' => 'required',
    'mother.firstname' => 'required',
    'mother.lastname' => 'required',
    'mother.email' => 'required|email',
    'children' => 'array|null',
]
```

---

📌 Notes
-------

[](#-notes)

- This module is **under active development** — more features and integrations are coming soon!
- Built for flexibility, testability, and ease of use in **Magento 2 backend and frontend service layers**.

---

💬 Stay Connected
----------------

[](#-stay-connected)

Got feedback or feature requests? PRs and ideas are welcome!

---

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance61

Regular maintenance activity

Popularity19

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~31 days

Total

2

Last Release

248d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e7840de74587351db6f9c8ec49c283e5a11ee3070734d1283820eafcaf1d95eb?d=identicon)[rajeevktomy](/maintainers/rajeevktomy)

---

Top Contributors

[![rajeev-k-tomy](https://avatars.githubusercontent.com/u/7589113?v=4)](https://github.com/rajeev-k-tomy "rajeev-k-tomy (23 commits)")

### Embed Badge

![Health badge](/badges/rkt-magento-data/health.svg)

```
[![Health](https://phpackages.com/badges/rkt-magento-data/health.svg)](https://phpackages.com/packages/rkt-magento-data)
```

###  Alternatives

[tig/postnl-magento2

TIG Magento 2 PostNL extension

58544.2k4](/packages/tig-postnl-magento2)[lillik/magento2-price-decimal

Magento 2 Price Decimal Precision

111147.5k](/packages/lillik-magento2-price-decimal)[nosto/module-nostotagging

Increase your conversion rate and average order value by delivering your customers personalized product recommendations throughout their shopping journey.

27659.1k4](/packages/nosto-module-nostotagging)[magepal/magento2-customeraccountlinksmanager

Customer Account Links Manager for Magento2 allows you to quickly and easily remove unwanted links from customer account dashboard

4084.9k](/packages/magepal-magento2-customeraccountlinksmanager)[doofinder/doofinder-magento2

Doofinder module for Magento 2

13204.0k1](/packages/doofinder-doofinder-magento2)[magepal/magento2-form-field-manager

Customer and Address Form Fields Manager for Magento2

293.8k](/packages/magepal-magento2-form-field-manager)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
