PHP code example of romanzipp / dto

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

    

romanzipp / dto example snippets


use romanzipp\DTO\AbstractData;
use romanzipp\DTO\Attributes\Required;

class DummyData extends AbstractData
{
    #[Required]
    public string $name;

    public ?string $nickname;

    public string|int $height;

    public DateTime $birthday;

    public bool $subscribeNewsletter = false;
}

$data = new DummyData([
    'name' => 'Roman',
    'height' => 180,
]);

use romanzipp\DTO\AbstractData;
use romanzipp\DTO\Attributes\Required;

class DummyData extends AbstractData
{
    #[Required]
    public string $name;
}

$data = new DummyData([]);

use romanzipp\DTO\AbstractData;

class DummyData extends AbstractData
{
    public string $firstName;

    public DummyData $childData;
    
    /** @var self[] */
    public array $children = [];
}

$data = new DummyData([
    'firstName' => 'Roman',
    'childData' => new DummyData([
        'firstName' => 'Tim',
     ]),
    'children' => [
        new DummyData([
            'firstName' => 'Tom'
        ]),
    ],
]);

$data->toArray();
// [
//    'firstName' => 'Roman',
//    'childData' => ['firstName' => 'Tim']
//    'children' => [
//        ['firstName' => 'Tom']
//    ] 
// ];

use romanzipp\DTO\AbstractData;
use romanzipp\DTO\Cases;

class DummyData extends AbstractData
{
    public string $firstName;
}

$data = new DummyData([
    'firstName' => 'Roman',
]);

$data->toArrayConverted(Cases\CamelCase::class);  // ['firstName' => 'Roman'];
$data->toArrayConverted(Cases\KebabCase::class);  // ['first-name' => 'Roman'];
$data->toArrayConverted(Cases\PascalCase::class); // ['FirstName' => 'Roman'];
$data->toArrayConverted(Cases\SnakeCase::class);  // ['first_name' => 'Roman'];

use romanzipp\DTO\AbstractData;
use romanzipp\DTO\Attributes\Flexible;

#[Flexible]
class DummyData extends AbstractData
{
    public string $name;
}

$data = new DummyData([
    'name' => 'Roman',
    'website' => 'ich.wtf',
]);

$data->toArray(); // ['name' => 'Roman', 'website' => 'ich.wtf];