-
Hello there, Using output DTOs in API-Platform 2.x could be done by using data transformers, meaning we could transform each returned item from the persistence layer to a representation meant for output. In API-Platform 3.x, this can be achieved by some sort of overriding/decorating the persistence layer itself, by creating a state provider. This raises a question we didn't need to ask in API-Platform 2.x, and which is not covered by the documentation: how do we keep pagination information when using different representations? TL; DR:
ReproductionConsider that resource: namespace App\Entity;
use ApiPlatform\Metadata\GetCollection;
use App\State\BookCollectionProvider;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
#[GetCollection(
output: BookOutput::class,
provider: BookCollectionProvider::class,
)]
class Book
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
public ?int $id = null;
#[ORM\Column(length: 255)]
public ?string $name = null;
} with the following representation: namespace App\Entity;
final class BookOutput
{
public ?int $id = null;
public ?string $name = null;
public string $isbn = 'some-hardcoded-isbn';
} And its provider: namespace App\State;
use ApiPlatform\Doctrine\Orm\State\CollectionProvider;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Entity\BookOutput;
use Generator;
final readonly class BookCollectionProvider implements ProviderInterface
{
public function __construct(
private CollectionProvider $collectionProvider,
) {
}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): Generator
{
$results = $this->collectionProvider->provide($operation, $uriVariables, $context);
foreach ($results as $book) {
$output = new BookOutput();
$output->id = $book->id;
$output->name = $book->name;
yield $output;
}
}
} By returning a generator which will map each |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You can preserve
Also you could try |
Beta Was this translation helpful? Give feedback.
You can preserve
hydra:totalItems
with ArrayPaginator: