PHP code example of lodipay / php-dto

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

    

lodipay / php-dto example snippets




namespace Tsetsee\DTO\Tests\DTO;

use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Spatie\DataTransferObject\Attributes\CastWith;
use Spatie\DataTransferObject\Attributes\MapTo;
use Tsetsee\DTO\Casters\CarbonCaster;
use Tsetsee\DTO\DTO\TseDTO;

class TestDTO extends TseDTO
{
    public string $firstName;
    public string $lastName;
    public ?string $familyName = null;
    public ?int age = null;
}
...

$dto = new TestDTO([
  'firstName' => 'Tsetsentsengel',
  'lastName' => 'Munkhbayar',
  // 'familyName' => 'Galzuud',
  'age' => 31,
]);

var_dump($dto->toArray());
...

[Output]
array() {
  ["firstName"] =>
  string(14) "Tsetsentsengel"
  ["lastName"] =>
  string(10) "Munkhbayar"
  ["age"] =>
  int 31
}


  

  namespace Tsetsee\DTO\Tests\DTO;

  use Symfony\Component\Serializer\Annotation\Context;
  use Tsetsee\DTO\Serializer\Normalizer\CarbonNormalizer;
  use Tsetsee\DTO\DTO\TseDTO;
  use Carbon\CarbonImmutable;

  class TestDTO extends TseDTO
  {
      #[Context(
          normalizationContext: [
              CarbonNormalizer::FORMAT_KEY => 'c',
          ],
          denormalizationContext: [
              CarbonNormalizer::FORMAT_KEY => 'm-d-Y H:i:s',
          ],
      )]
      public ?CarbonImmutable $date = null;
  }
  



namespace Tsetsee\DTO\Tests\DTO;

use Carbon\Carbon;
use Tsetsee\DTO\DTO\TseDTO;
use Symfony\Component\Serializer\Annotation\Context;
use Tsetsee\DTO\Serializer\Normalizer\CarbonNormalizer;

class TestDTO extends TseDTO
{
    #[Context(
        denormalizationContext: [
            CarbonNormalizer::FORMAT_KEY => 'X',
        ],
    )]
    public ?Carbon $dateFromTimestamp = null;
}



namespace Tsetsee\DTO\Tests\DTO;

use Carbon\Carbon;
use Tsetsee\DTO\DTO\TseDTO;
use Symfony\Component\Serializer\Annotation\Context;
use Tsetsee\DTO\Serializer\Normalizer\CarbonNormalizer;

class TestDTO extends TseDTO
{
    /**
     * @var array<ChildDTO>
     */
    public array $children = [];

    public function addChildren(ChildDTO $children): void
    {
        $this->children[] = $children;
    }
}
bash
$ composer