PHP code example of methorz / http-dto

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

    

methorz / http-dto example snippets


public function handle(ServerRequestInterface $request): ResponseInterface
{
    // 1. Get request body
    $data = $request->getParsedBody();

    // 2. Map to DTO
    $dto = new CreateItemRequest(
        name: $data['name'] ?? '',
        description: $data['description'] ?? ''
    );

    // 3. Validate DTO
    $violations = $this->validator->validate($dto);
    if (count($violations) > 0) {
        return new JsonResponse(['errors' => ...], 422);
    }

    // 4. Execute service
    $result = $this->service->execute($dto);

    // 5. Serialize response
    return new JsonResponse($result->toArray(), 201);
}

public function __invoke(
    ServerRequestInterface $request,
    CreateItemRequest $dto  // ← Automatically mapped, validated, and injected!
): ItemResponse {           // ← Automatically serialized to JSON!
    return $this->service->execute($dto);  // One line! 🎉
}

use Symfony\Component\Validator\Constraints as Assert;

final readonly class CreateItemRequest
{
    public function __construct(
        #[Assert\NotBlank(message: 'Name is    ) {}
}

use Methorz\Dto\Response\JsonSerializableDto;

final readonly class ItemResponse implements JsonSerializableDto
{
    public function __construct(
        public string $id,
        public string $name,
        public string $description,
    ) {}

    public function jsonSerialize(): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
        ];
    }

    public function getStatusCode(): int
    {
        return 201; // Created
    }
}

use Methorz\Dto\Handler\DtoHandlerInterface;

final readonly class CreateItemHandler implements DtoHandlerInterface
{
    public function __construct(
        private CreateItemService $service,
    ) {}

    public function __invoke(
        ServerRequestInterface $request,
        CreateItemRequest $dto  // ← Injected automatically!
    ): ItemResponse {           // ← Serialized automatically!
        return $this->service->execute($dto);
    }

    // PSR-15 compatibility method (not used directly)
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        return $this->__invoke($request, new CreateItemRequest('', ''));
    }
}

use MethorZ\Dto\Factory\DtoHandlerWrapperFactory;
use MethorZ\Dto\RequestDtoMapperInterface;
use MethorZ\Dto\Exception\MappingException;
use MethorZ\Dto\Exception\ValidationException;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;

public function getDependencies(): array
{
    return [
        'factories' => [
            // DTO Handler Wrapper Factory
            DtoHandlerWrapperFactory::class => function (ContainerInterface $container) {
                return new DtoHandlerWrapperFactory(
                    $container->get(RequestDtoMapperInterface::class),
                    $container->get('dto.error_handler'),
                );
            },
        ],
        'services' => [
            // Error handler for DTO validation/mapping failures
            'dto.error_handler' => function (ValidationException|MappingException $e): ResponseInterface {
                if ($e instanceof ValidationException) {
                    return new JsonResponse([
                        'success' => false,
                        'errors' => $e->getErrors(),
                    ], 422);
                }
                return new JsonResponse([
                    'success' => false,
                    'error' => $e->getMessage(),
                ], 400);
            },
        ],
    ];
}

use Item\Application\Handler\CreateItemHandler;
use MethorZ\Dto\Factory\DtoHandlerWrapperFactory;

public function getRoutes(): array
{
    return [
        [
            'allowed_methods' => ['POST'],
            'path'            => '/api/v1/items',
            'middleware'      => [
                DtoHandlerWrapperFactory::class . '::wrap:' . CreateItemHandler::class,
            ],
        ],
    ];
}