PHP code example of jnariai / simple-dto

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

    

jnariai / simple-dto example snippets


use SimpleDTO\DTO;

final readonly class MyDTO extends DTO
{
    public function __construct(
        public bool $property_bool,
        public ?string $property_string,
        public string $sensitive_data,
    ) {}
}

$myDTO = MyDTO::from([
    'property_bool' => true,
    'sensitive_data' => 'sensitive data',
]);

// You don't need to pass properties that can be null, it will automatically be set to null
/* MyDTO {
  +property_bool: true
  +property_string: null
  +sensitive_data: "sensitive data"
}
*/ 

$myDTO->toArray(); // ['property_bool' => true, 'property_string' => null, 'sensitive_data' => 'sensitive data']
$myDTO->toJson(); // {"property_bool":true,"property_string":null,"sensitive_data":"sensitive data"}

use SimpleDTO\DTO;

#[NonNullOutput]
final readonly class MyDTO extends DTO
{
    public function __construct(
        public bool $property_bool,
        public ?string $property_string,
        public string $sensitive_data,
    ) {}
}

$myDTO->toArray(); // ['property_bool' => true, 'sensitive_data' => 'sensitive data']
$myDTO->toJson(); // {"property_bool":true,"sensitive_data":"sensitive data"}

use SimpleDTO\DTO;

final readonly class MyDTO extends DTO
{
    public function __construct(
    public bool $property_bool,
    public ?string $property_string,
    #[Hidden]
    public string $sensitive_data,
    ) {}
}

$myDTO->toArray(); // ['property_bool' => true, 'property_string' => null]
$myDTO->toJson(); // {"property_bool":true,"property_string":null}