PHP code example of perfilov / php-dto-packer

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

    

perfilov / php-dto-packer example snippets


use DtoPacker\AbstractDto;

class Family extends AbstractDto
{
    public string $surname;
    protected array|Person $persons;
    public bool $hasCar;
}

class Person extends AbstractDto
{
    public string $name;
    public \DateTime $birthday;
    protected PersonTypeEnum $type;
    protected array|string $friends;
}

enum PersonTypeEnum
{
    case HUSBAND;
    case WIFE;
    case CHILD;
}

$family = new Family([
    'surname' => 'Perfilov',
    'persons' => [
        [ // from array
            'name'      => 'Stanislav',
            'birthday'  => '1987-12-13T12:05:55+03:00',
            'type'      => 'HUSBAND',
            'friends'   => ['Elon Musk', 'Guy Ritchie'],
        ], new Person([ // or object
            'name'      => 'Natali',
            'type'      => PersonTypeEnum::WIFE,
            'birthday'  => \DateTime::createFromFormat('d.m.Y', '28.11.1994'),
        ]),[
            'name'      => 'Leo',
            'type'      => 'CHILD',
        ],
    ],
]);

// or set it manually
$family->persons[2]->friends = ['Jason Statham', 'John Depp'];

$arr = $family->toArray();

Output: [
  "surname" => "Perfilov"
  "persons" => [
    [
      "name" => "Stanislav"
      "birthday" => "1987-12-13T12:05:55+03:00"
      "type" => "HUSBAND"
      "friends" => ["Elon Musk", "Guy Ritchie"]
    ], [
      "name" => "Natali"
      "birthday" => "1994-11-28T21:02:13+00:00"
      "type" => "WIFE"
    ], [
      "name" => "Leo"
      "type" => "CHILD"
      "friends" => ["Jason Statham", "John Depp"]
    ]
  ]
]

$json = (string)$family;

Output: {"surname":"Perfilov","persons":[{"name":"Stanislav","birthday":"1987-12-13T12:05:55+03:00","type":"HUSBAND","friends":["Elon Musk","Guy Ritchie"]},{"name":"Natali","birthday":"1994-11-28T21:11:57+00:00","type":"WIFE"},{"name":"Leo","type":"CHILD","friends":["Jason Statham","John Depp"]}]}

$family = new Family($json);
bash
composer