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/ */
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 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
}
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
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.