PHP code example of php-collective / symfony-dto

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

    

php-collective / symfony-dto example snippets


return [
    // ...
    PhpCollective\SymfonyDto\PhpCollectiveDtoBundle::class => ['all' => true],
];

use PhpCollective\Dto\Builder\Dto;
use PhpCollective\Dto\Builder\Field;
use PhpCollective\Dto\Builder\Schema;

return Schema::create()
    ->dto(Dto::create('User')->fields(
        Field::int('id'),
        Field::string('name'),
        Field::string('email')->nullable(),
    ))
    ->toArray();

use App\Dto\UserDto;

$user = new UserDto([
    'id' => 1,
    'name' => 'John Doe',
    'email' => '[email protected]',
]);

return $this->json($user->toArray());

use App\Dto\UserDto;
use PhpCollective\SymfonyDto\Mapper\DtoMapper;

$dto = DtoMapper::fromArray(['name' => 'Mark'], UserDto::class);

$dtos = DtoMapper::fromIterable($rows, UserDto::class);
$collection = DtoMapper::fromCollection($doctrineCollection, UserDto::class);

// Generic pagination wrapper
$pagination = DtoMapper::fromPaginated(
    items: $pageItems,
    total: $total,
    perPage: $perPage,
    page: $page,
    dtoClass: UserDto::class,
);

use PhpCollective\SymfonyDto\Http\DtoJsonResponse;

return DtoJsonResponse::fromDto($dto);
// or
return DtoJsonResponse::fromCollection($dtos);

use PhpCollective\SymfonyDto\Attribute\MapRequestDto;

#[Route('/users', methods: ['POST'])]
public function create(#[MapRequestDto] UserDto $dto): Response
{
    // $dto is built from request data
}

Field::array('roles', 'Role'),  // Role[] collection
Field::array('tags', 'string'), // string[] collection

use PhpCollective\SymfonyDto\Validation\DtoConstraintBuilder;
use Symfony\Component\Validator\Validation;

$constraint = DtoConstraintBuilder::fromDto(new UserDto());
$violations = Validation::createValidator()->validate($data, $constraint);

use PhpCollective\SymfonyDto\AutoMapper\DtoAutoMapperInterface;

class UserController extends AbstractController
{
    public function __construct(
        private DtoAutoMapperInterface $dtoMapper,
    ) {}

    #[Route('/users/{id}')]
    public function show(User $user): JsonResponse
    {
        $dto = $this->dtoMapper->toDto($user, UserDto::class);

        return $this->json($dto->toArray());
    }
}
bash
composer