Created
April 7, 2024 18:24
-
-
Save mmouih/1182c10be2d2f4d442da48ac3de94ba7 to your computer and use it in GitHub Desktop.
Mapping invoice entity to DTO to safeguard our entity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Contract; | |
class InvoiceContract | |
{ | |
public readonly int $id; | |
public readonly string $invoiceNumber; | |
public readonly string $amount; | |
public readonly \DateTimeInterface $createdAt; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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