PHP code example of kirillbdev / php-data-transformer

1. Go to this page and download the library: Download kirillbdev/php-data-transformer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kirillbdev / php-data-transformer example snippets


namespace MyApp\Dto;

class UserDto
{
    public $id;
    
    public $firstname;
}

namespace MyApp;

use kirillbdev\PhpDataTransformer\DataTransformer;
use kirillbdev\PhpDataTransformer\DataObject\ArrayDataObject;
use MyApp\Dto\UserDto;

$dto = DataTransformer::transform(UserDto::class, new ArrayDataObject([
    'id' => 1,
    'firstname' => 'Jon'
]));

namespace MyApp\Dto;

class UserDto
{
    public $id;
    
    /**
     * We need to receive this property from first_name key.
     * @ReceiveFrom("first_name")
     */
    public $firstname;
}

namespace MyApp;

use kirillbdev\PhpDataTransformer\DataTransformer;
use kirillbdev\PhpDataTransformer\DataObject\ArrayDataObject;
use MyApp\Dto\UserDto;

$dto = DataTransformer::transform(UserDto::class, new ArrayDataObject([
    'id' => 1,
    'first_name' => 'Jon' // Custom key that differ of our DTO property.
]));

namespace MyApp\Dto;

class UserDto
{
    /**
     * We want to cast this property to integer.
     * @Cast("int")
     */
    public $id;
}

namespace MyApp\Dto;

class UserDto
{
    /**
     * We want to cast this property to UserRoleDto.
     * @Cast(<MyApp\Dto\UserRole>)
     */
    public $role;
}

namespace MyApp\Dto;

use kirillbdev\PhpDataTransformer\Contracts\DataObjectInterface;

class UserDto
{
    public $id;
    
    /**
     * We need to receive this property as combination of two keys (firstname and lastname).
     */
    public $fullName;
    
    /**
     * Let's implement custom transformation method.
     * 
     * @param DataObjectInterface $dataObject
     * @return string|null
     */
    public function transformFullNameProperty(DataObjectInterface $dataObject)
    {
        return $dataObject->get('firstname') . ' ' . $dataObject->get('lastname');
    }
}