PHP code example of simonisme / array-to-dto

1. Go to this page and download the library: Download simonisme/array-to-dto 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/ */

    

simonisme / array-to-dto example snippets




class EmailAddress
{
	public $email;

	public function __construct(string $email)
	{
		$this->email = $email;
	}

}

$arrayToDtoParse = new ArrayToDtoParser();
$result  = $arrayToDtoParse->parseToDto(EmailAddress::class, [
    '[email protected]';
]);

//  $result variable contains correct EmailAddress object
echo $result->email; // [email protected]


class User
{
	public $emailAddress;
	public $number;
	public $birthDate;

	public function __construct(EmailAddress $emailAddress, string $name, \DateTime $birthDate)
	{
		$this->emailAddress = $emailAddress;
		$this->number = $name;
		$this->birthDate = $birthDate;
	}
}

class Nested
{
	public $user;
	public $emailAddress;

	public function __construct(User $user, EmailAddress $emailAddress)
	{
		$this->user = $user;
		$this->emailAddress = $emailAddress;
	}
}

class EmailAddress
{
	public $email;

	public function __construct(string $email)
	{
		$this->email = $email;
	}
}

class Dto
{
	public $user;
	public $nested;

	public function __construct(User $user, Nested $nested)
	{
		$this->user = $user;
		$this->nested = $nested;
	}
}

$arrayToDtoParse = new ArrayToDtoParser();
$result  = $arrayToDtoParse->parseToDto(Dto::class, [
    'user' => [
        'emailAddress' => '[email protected]',
        'name' => 'Simon',
        'birthDate' => '1991-01-02',
    ],
    'nested' => [
        'user' => [
            'emailAddress' => '[email protected]',
            'name' => 'Simon',
            'birthDate' => '1991-01-02',
        ],
        'emailAddress' => '[email protected]'
    ]
]);