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-04-22 (9 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.9.0MIT/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
Number 4
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\CredentialsTransfer;
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';

/** @var string $value */
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());

echo <<<'STORY'
=================================================================
             Try protected properties (partly immutable)
=================================================================

STORY;
$credentialsTransfer = new CredentialsTransfer([
   
CredentialsTransfer::LOGIN => 'jan.kowalski',
   
CredentialsTransfer::TOKEN => 'some-random-token',
]);

echo
"Login: $credentialsTransfer->login\n";
echo
"Token: $credentialsTransfer->token\n";


Details

Transfer Object Generator

CI workflow License PHP Version Require Latest Stable Version

Transfer Object Generator

Would you like to build Symfony-compatible Transfer Objects easily?

You're in the right place! ?

Build Transfer Object by Blueprint

Imagine you have a Rest API response:

{
    "firstName": "Jan",
    "lastName": "Kowalski"
}

Running the following interactive console command:

$ ./vendor/bin/definition-generate

Generates a YML definition file:

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

Then, running another console command:

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

Builds the Transfer Object:

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

Key Features

  • Symfony-compatible: * includes Symfony console commands: TransferGeneratorCommand and DefinitionGeneratorCommand * includes Symfony services: TransferGeneratorFacade and DefinitionGeneratorFacade * Transfer Objects are mappable with Symfony request
  • Transfer Object: * implements methods: `fromArray()`, `toArray()`, and `toFilterArray()` * implements standard interfaces: `IteratorAggregate`, `JsonSerializable`, and `Countable` * supports embedded Transfer Objects, collections as well as `BackedEnum`, nullable and not nullable property types * supports asymmetric property visibility * supports custom Data Transfer Object (DTO)

Installation

Composer installation:

$ composer require picamator/transfer-object

Usage Tests

Definition Files and Transfer Object generators have been tested against API responses such as:

Test Scenario

  1. Rest API response is used as a blueprint to generate Definition Files
  2. Transfer Objects are generated based on Definition Files
  3. Transfer Object instance is created with the API response
  4. Transfer Object is converted back to the array
  5. The converted array is compared with the API response

In all cases, data 100% are matched ?.

For detailed information, please check DefinitionGeneratorFacadeTest.

Service Samples

Practice

Definition Files and Transfer Objects generators use Transfer Objects.

Acknowledgment

Many thanks for your contribution, support, feedback and simply using the Transfer Object Generator! ??

Contribution

If you find this project useful, please ? star 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
  • Submit a pull request

Here is a Contribution Guide.

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 (510)  
File Role Description
Files folder image.github (6 files, 2 directories)
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 .env.dist Data Auxiliary data
Accessible without login Plain text file .env.dist Data Auxiliary data
Accessible without login Plain text file .env.dist Data Auxiliary data
Accessible without login Plain text file .env.dist Data Auxiliary data
Accessible without login Plain text file .env.dist Data Auxiliary data
Accessible without login Plain text file .env.dist 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  
 76%
Total:25
This week:3
All time:11,257
This week:20Up