PHP Classes

How to Generate a PHP Data Transfer Object from an Array or YML File Using the Package Transfer Object: Generate transfer objects using property hooks

Recommend this page to a friend!
  Info   Example   Screenshots   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2025-02-09 (20 days ago) RSS 2.0 feedNot enough user ratingsTotal: 25 This week: 3All time: 11,257 This week: 20Up
Version License PHP version Categories
transfer-object 1.5.4MIT/X Consortium ...8.4Console, Code Generation, Design Patt..., P...
Description 

Author

This package can generate transfer objects using property hooks.

It can take a definition of a transfer object as an array or in a file in the YML format and generate a code file for the described transfer object class.

The package uses a template to define the transfer object class code using PHP class property hooks to implement the code of functions that are called to set or get the transfer object class variable values.

Innovation Award
PHP Programming Innovation award nominee
January 2025
Nominee
Vote
A data transfer object is an object that is used in applications to pass information between different processes.

This package can quickly generate data transfer object classes from object class definitions passed as arrays or configuration files in YML format.

It uses PHP property hooks to simplify the definition of the generated data transfer object class.

Manuel Lemos
Picture of Sergii Pryz
  Performance   Level  
Innovation award
Innovation award
Nominee: 5x

 

Example

<?php

declare(strict_types=1);

use
Picamator\Doc\Samples\TransferObject\Enum\CountryEnum;
use
Picamator\Doc\Samples\TransferObject\Generated\TransferGenerator\AgentTransfer;
use
Picamator\Doc\Samples\TransferObject\Generated\TransferGenerator\CustomerTransfer;
use
Picamator\Doc\Samples\TransferObject\Generated\TransferGenerator\MerchantTransfer;
use
Picamator\TransferObject\TransferGenerator\TransferGeneratorFacade;

require_once
__DIR__ . '/../../vendor/autoload.php';

echo <<<'STORY'
==============================================================
           Generate Transfer Objects
                  with notice
     for demonstration exception handling was skipped
==============================================================

STORY;
$configPath = __DIR__ . '/config/transfer-generator/generator.config.yml';
new
TransferGeneratorFacade()->generateTransfersOrFail($configPath);

echo <<<'STORY'
======================================================
        Try newly Generated Transfer Objects
======================================================

STORY;
$customerTransfer = new CustomerTransfer();
$customerTransfer->firstName = 'Jan';
$customerTransfer->lastName = 'Kowalski';

foreach (
$customerTransfer as $key => $value) {
    echo
"key: $key, value: $value\n";
}

echo
"CustomerTransfer properties count: {$customerTransfer->count()}\n}.";

$merchantTransfer = new MerchantTransfer();
$merchantTransfer->merchantReference = 'PL-234-567';
$merchantTransfer->country = CountryEnum::PL;
$merchantTransfer->isActive = true;

var_dump($merchantTransfer->toArray());

echo <<<'STORY'
======================================================
             Try how fromArray() works
======================================================

STORY;
$agentTransfer = new AgentTransfer()
    ->
fromArray([
       
AgentTransfer::CUSTOMER => [
           
CustomerTransfer::FIRST_NAME => 'Max',
           
CustomerTransfer::LAST_NAME => 'Mustermann',
        ],
       
AgentTransfer::MERCHANTS => [
            [
               
MerchantTransfer::COUNTRY => 'DE',
               
MerchantTransfer::MERCHANT_REFERENCE => 'DE-234-567',
               
MerchantTransfer::IS_ACTIVE => false,
            ], [
               
MerchantTransfer::COUNTRY => 'PL',
               
MerchantTransfer::MERCHANT_REFERENCE => 'PL-774-444',
               
MerchantTransfer::IS_ACTIVE => true,
            ],
        ],
       
'uuid' => '123-123-123-123',
    ]);

var_dump($agentTransfer->toArray());


Details

Transfer Object Generator

CI workflow License PHP Version Require Latest Stable Version

Transfer Object Generator

Would you like to build lightweight Transfer Objects (TO) easily? You're in the right place!

Build TOs Using an Array as Blueprint

Imagine you have an array:

$data = [
    'firstName' => 'Jan',
    'lastName' => 'Kowalski'
];

TO facade method helps to convert array into YML definition file:

Customer:
  firstName:
    type: string
  lastName:
    type: string

Generator console command builds TO based on definition file:

$customerTransfer = new CustomerTransfer();
$customerTransfer->firstName = 'Jan';
$customerTransfer->lastName = 'Kowalski';

How it works in action can be found on Wiki: - Try Sample to generate Definition files - Try Sample to generate TOs - Try Advanced Sample to generate TOs

Key Features

  • Interface methods: implements `fromArray()`, `toArray()`
  • Standard interfaces: implements `IteratorAggregate`, `JsonSerializable`, and `Countable`
  • Lightweight: TO includes only data without any business logic
  • Nullable: supports both attribute types nullable and not nullable (`required:`)
  • BackedEnum: supports `BackedEnum`
  • Adaptable: compatible with custom Data Transfer Object (DTO) implementation

Installation

Composer installation:

$ composer require picamator/transfer-object

Usage

Terminal

Run command bellow to generate Transfer Objects:

$ ./vendor/bin/generate-transfer [-c|--configuration CONFIGURATION]

Please check Wiki for more details: - Command Configuration - Definition File

Facade Interface

Facade interface DefinitionGeneratorFacadeInterface is used to generate YML definition file based on array.

Please check Wiki for more details: - Facade Interfaces - Visualizing Diagrams

Acknowledgment

Many thanks for your contribution, supports, feedback and simply using Transfer Object Generator!

Contribution

If you find this project useful, please add a star to the repository. Follow the project to stay updated with all activities. If you have suggestions for improvements or new features, feel free to create an issue or submit a pull request. Here is a Contribution Guide.

Please note that this project is released with a Code of Conduct. By participating in this project and its community, you agree to abide by those terms.

License

Transfer Object Generator is free and open-source software licensed under the MIT License. For more details, please see the LICENSE file.


Screenshots (2)  
  • doc/img/transfer-object-generator.jpg
  • Transfer Object Generator
  Files folder image Files (337)  
File Role Description
Files folder image.github (1 directory)
Files folder imagebin (1 file)
Files folder imageconfig (1 file, 1 directory)
Files folder imagedoc (1 directory)
Files folder imagedocker (1 file, 1 directory)
Files folder imagesrc (7 directories)
Files folder imagetests (2 directories)
Accessible without login Plain text file .editorconfig Data Auxiliary data
Accessible without login Plain text file captainhook.json Data Auxiliary data
Accessible without login Plain text file CODE_OF_CONDUCT.md Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file composer.lock Data Auxiliary data
Accessible without login Plain text file CONTRIBUTING.md Data Auxiliary data
Accessible without login Plain text file docker-compose.yml Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file phpcs.xml Data Auxiliary data
Accessible without login Plain text file phpstan.neon Data Auxiliary data
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation
Accessible without login Plain text file SECURITY.md Data Auxiliary data

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 99%
Total:25
This week:3
All time:11,257
This week:20Up