Skip to content

Instantly share code, notes, and snippets.

@mmouih
Created April 7, 2024 18:24
Show Gist options
  • Save mmouih/1182c10be2d2f4d442da48ac3de94ba7 to your computer and use it in GitHub Desktop.
Save mmouih/1182c10be2d2f4d442da48ac3de94ba7 to your computer and use it in GitHub Desktop.
Mapping invoice entity to DTO to safeguard our entity
<?php
namespace App\Contract;
class InvoiceContract
{
public readonly int $id;
public readonly string $invoiceNumber;
public readonly string $amount;
public readonly \DateTimeInterface $createdAt;
}
<?php
//...
use App\Mapper\EntityMapperInterface;
use Symfony\Component\Serializer\SerializerInterface;
#[Route('/invoice')]
class InvoiceController extends AbstractController
{
public function __construct(
private readonly EntityMapperInterface $entityMapper,
private readonly SerializerInterface $serializer
) {
}
#[Route('/{id}', name: 'invoice_show', methods: ['GET'])]
public function show(Invoice $invoice): JsonResponse
{
$invoiceContract = $this->entityMapper->map($invoice, InvoiceContract::class);
$jsonData = $this->serializer->serialize($invoiceContract, 'json');
return new JsonResponse($jsonData, 200, [], true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment