PHP code example of bssphp / dto

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

    

bssphp / dto example snippets


use bssphp\dto\AbstractData;
use bssphp\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 bssphp\dto\AbstractData;
use bssphp\dto\Attributes\Required;

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

$data = new DummyData([]);

use bssphp\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 bssphp\dto\AbstractData;
use bssphp\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 bssphp\dto\AbstractData;
use bssphp\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];