PHP code example of bpartner / dto

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

    

bpartner / dto example snippets


class DemoDto extends DtoAbstract
{
    //Optional
    protected const CLASS_FORM_REQUEST = UpdateUserFormRequest::class;
    
    /**
    * DTO fields
    */
    public string $name;
    public Carbon $date;
    public DtoOtherObject $otherObject;
    
    /** @var collection<\App\Dto\DtoOtherObject>  */
    public Collection $objectsCollection;
    
    /** @var array<\App\Dto\DtoOtherObject>  */
    public array $objectsArray;
    
    /** @var collection<\App\Dto\DtoOtherObject>  */
    public array $objectsArrayOfCollection;
    }

//In any place of your code
$data = request()->all(); //array data
$dto = Dto::build(DemoDto::class, $data);

/**
 * In controller
 * 
 * Create FormRequest and assign to CLASS_FORM_REQUEST const in DTO
 * 
 */ 
public function store(DemoDto $dto)
{
    //Use $dto made from UpdateUserFormRequest
}

$name = $dto->name;
$objectCollection = $dto->objectsCollection;

class DemoDto extends DtoAbstract
{
    public string $firstName;
}

$inputData = [
    'first_name' => 'John Doe'
];

$dto = Dto::build(DemoDto::class, $inputData, DtoFactory::CAMEL_CASE);


public static function withMap(array $data): DtoInterface
{
    $mappedData = [
        'dto_param' => $data['some_param'],
    ];
    
    return new static($mappedData);
}

//Client code
$dto = Dto::build(DemoDto::class, request()->all());

$array = $dto->toArray();

array:4 [
  "name" => "Demo data"
  "date" => "06-11-2021"
  "phone" => array:2 [
    "type" => "home"
    "number" => "500-123-123"
  ]
  "phones" => array:2 [
    0 => array:2 [
      "type" => "work"
      "number" => "500-123-122"
    ]
    1 => array:2 [
      "type" => "private"
      "number" => "500-123-124"
    ]
  ]
]

$flat = $dto->flatArray();

array:5 [                       
  "name" => "Demo data"         
  "date" => "06-11-2021"        
  "type" => "home"              
  "number" => "500-123-123"     
  "phones" => array:2 [         
    0 => array:2 [              
      "type" => "work"          
      "number" => "500-123-122" 
    ]                           
    1 => array:2 [              
      "type" => "private"       
      "number" => "500-123-124" 
    ]                           
  ]                             
]